at函数
语法:
1 2 |
reference at(size_type __n); const_reference at(size_type __n) const; |
at() 返回指定位置的元素
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * @brief Provides access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } /** * @brief Provides access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1(10, 0); vector<int> v2(10, 2); for(int i=0;i<v2.size();i++){ cout<<v2.at(i)<<","; } cout<<endl; } |
测试结果:
1 |
2,2,2,2,2,2,2,2,2,2, |