std::vector的一些使用注意事项

时间:2022-11-21 17:47:23

std::vector的一些使用注意事项

  • 使用at()函数而不是operator[]:理由是at()可以抛出invalid vector[T] subscript异常,而operator[]不会做范围检查。因此,at()函数更加安全。
  • 使用vector的assign函数复制一个vector:
123456789101112131415161718192021222324252627282930313233 include
"stdafx.h"
#include
<vector>
#include
<iostream>
 int main( ){    using namespace std;    vector<int> v1, v2, v3;    vector<int>::iterator iter;     v1.push_back(10);    v1.push_back(20);    v1.push_back(30);    v1.push_back(40);    v1.push_back(50);     cout << "v1 = " ;    for (iter = v1.begin(); iter != v1.end(); iter++)        cout << *iter << " ";    cout << endl;     v2.assign(v1.begin(), v1.end());    cout << "v2 = ";    for (iter = v2.begin(); iter != v2.end(); iter++)        cout << *iter << " ";    cout << endl;     v3.assign(7, 4) ;    cout << "v3 = ";    for (iter = v3.begin(); iter != v3.end(); iter++)        cout << *iter << " ";    cout << endl;}
s st s st