使用两种方法来访问vector:
1、 vector::at(idx) --> 传回索引idx所指的数据,如果idx越界,抛出out_of_range
2、 vector::operator[]
operator[]主要是为了与C语言进行兼容。它可以像C语言数组一样操作。但at()是我们的首选,因为at()进行了边界检查,如果访问超过了vector的范围,将抛出一个例外。由于operator[]容易造成一些错误,所有我们很少用它,下面进行验证一下:
分析下面的代码:
vector<int> v;
v.reserve(10);
for(int i=0; i<7; i++) {
v.push_back(i); //在V的尾部加入7个数据
}
// not bounds checked - will not throw
int iVal2 = v.at(7);
// bounds checked - will throw if out of range
}
catch(const exception& e) {
cout << e.what();
try {
int iVal1 = v[7];
}