vector::at
原创
©著作权归作者所有:来自51CTO博客作者wx62f49e890a843的原创作品,请联系作者获取转载授权,否则将追究法律责任
Access element :
Returns a reference to the element at position n in the vector.
The function automatically checks whether n is within the bounds of valid elements in the vector, throwing anout_of_range exception if it is not (i.e., if n is greater or equal than its size). This is in contrast with memberoperator[], that does not check against bounds.
翻译:
XXX.at(index);
返回索引 index 所指的数据,即为了访问对应index中存储的数据,如果index越界,则抛出out_of_range。
// vector::at
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector1 (10); // 10 zero-initialized ints
std::vector<int>myvector2 (10);
// assign some values:
for (unsigned i=0; i<myvector1.size(); i++)
myvector1.at(i)=1;
std::cout << "myvector1 contains:";
for (unsigned i=0; i<myvector1.size(); i++)
std::cout << ' ' << myvector1.at(i);
std::cout << '\n';
//-------------------------------------------
for (unsigned i=0; i<myvector2.size(); i++)
myvector2.at(i)=i;
std::cout << "myvector2 contains:";
for (unsigned i=0; i<myvector2.size(); i++)
std::cout << ' ' << myvector2.at(i);
std::cout << '\n';
//下面的索引越界,导致抛出 out_of_range_exception
std::cout<<"\n";
std::cout<< myvector1.at(20); // out_of_range_exception
return 0;
}