// program below illustrates the // vector::insert() function #include<bits/stdc++.h> usingnamespace std; intmain() { // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return0; }
The vector elements are: 2310203040
v[i]与v.at(i)的区别
void f(vector<int> &v) { v[0]; // A v.at[0]; // B }
如果 v 非空,A 行和 B 行没有任何区别。如果 v 为空,B行会抛出 std::out_of_range 异常,A 行的行为未定义。
c++ 标准不要求 vector::operator[] 进行下标越界检查,原因是为了效率,总是强制下标越界检查会增加程序的性能开销。 设计vector是用来代替内置数组的,所以效率问题也应该考虑。不过使用 operator[] 就要自己承担越界风险了。
如果需要下标越界检查,请使用 at。
emplace_back vs push_back
emplace_back not copy and move object to container A similar member function exists, push_back, which either copies or moves an existing object into the container