std::vector::at
reference at (size_type n);
const_reference at (size_type n) const;
返回一个指向位置n的元素的引用。
The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater or equal than its size). This is in contrast with member operator[], that does not check against bounds.
该方法将自动检测n是否是在一个有效的范围,如果不是则将抛出out_of_range异常。
另一个对照的方法是operator[],这个方法不会检测数据的有效性。
例子:
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
int main(int argc,char **argv)
{
vector<int> vi({10,20,30});
cout<<"vi.at(1)="<<vi.at(1)<<endl;
cout<<"vi.at(10)="<<vi.at(10)<<endl;
}
运行结果:
可以看到,下标和数组一样,是从0开始的。
如果超出了范围,将会抛出异常。
Parameters
-
n
-
Position of an element in the container.
If this is greater than or equal to the vector size, an exception of type out_of_range is thrown.
Notice that the first element has a position of 0 (not 1).
Member type size_type is an unsigned integral type.
n是元素在vector中的位置。
如果n大于或者等于数组的size,那么将会抛出out_of_range异常。
注意,第一个元素的位置为0而不是1.
n的类型为unsigned intergral类型。
Return value
The element at the specified position in the container.返回值为元素在容器内指定位置的值。
If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.
如果vector是只读属性的,那么返回的是一个const_reference.否则,是一个普通的引用。
Member types reference and const_reference are the reference types to the elements of the container (see vector member types).
引用类型为容器元素的引用。
Example
| |
Output:
myvector contains: 0 1 2 3 4 5 6 7 8 9
|
Complexity
Constant.Iterator validity
No changes.Data races
The container is accessed (neither the const nor the non-const versions modify the container).
容器将被访问。
The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.返回的引用可以用来访问以及修改元素,同时这些操作都是安全的。
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.It throws out_of_range if n is out of bounds.
如果抛出异常,容器不会改变。当n不在范围内时抛出out_of_range异常。
//翻译的不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
2014-8-16
于GDUT