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;
}

vector::at_数据