vector::at
描述 (Description)
C ++函数std::vector::at()返回对向量中位置n处的元素的引用。
声明 (Declaration)
以下是std :: vector :: at()函数形式std :: vector header的声明。
C++98
reference at (size_type n);
const_reference at (size_type n) const;
参数 (Parameters)
n - 元素从容器中的位置。
返回值
如果n是有效向量索引,则返回指定位置的元素。
如果vector对象是常量限定的,则method返回常量引用,否则返回非常量引用。
异常 (Exceptions)
如果n无效,则抛出out_of_bound异常。
时间复杂
常数即O(1)
例子 (Example)
以下示例显示了std :: vector :: at()函数的用法。
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
auto il = {1, 2, 3, 4, 5};
vector<int> v(il);
for (int i = 0; i < v.size(); ++i)
cout << v.at(i) << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
1
2
3
4
5