set
1 // constructing sets 2 #include <iostream> 3 #include <set> 4 5 void checkin(std::set<int> & myset,int v) 6 { 7 if (myset.find(v) != myset.end()) 8 std::cout << "in " << std::endl; 9 else 10 std::cout << "not" << std::endl; 11 }; 12 int main() 13 { 14 15 int myints[] = { 10, 20, 30, 40, 50 }; 16 std::set<int> myset(myints, myints + 5); // range 17 18 checkin(myset, 10); 19 20 myset.erase(myset.find(10));//删除元素 21 checkin(myset, 10); 22 myset.insert(10);//添加元素 23 checkin(myset, 10); 24 25 system("pause"); 26 return 0; 27 }
c++ 如何检查一个元素是否在std :: set?
有一个更简单的等价的下面的代码:
myset.find(x) != myset.end()
检查许多STL容器中的存在的典型方法是:
const bool is_in = container.find(element) != container.end();
vector
创建:
// constructors used in the same order as described above:
std::vector<int> first; // empty vector of ints
std::vector<int> second (4,100); // four ints with value 100
std::vector<int> third (second.begin(),second.end()); // iterating through second
std::vector<int> fourth (third);
/m*n的二维vector,注意两个 "> "之间要有空格!
vector<vector <int> > ivec(m ,vector<int>(n));
最后一个元素
vector.back()
可以赋值
vector.back() = xxx;
头部插入元素
vector<int> a;
a.insert(a.begin(), 1);
a.insert(a.begin(), 2);
删除最后一个元素
pop_back();