在C ++ STL中从向量访问元素的不同方法
从向量访问元素的不同方法
1)使用[]运算符
语法:
vector_name[index]
参数:index–是向量中的位置。(从0开始的索引)
返回值:给定索引处的元素。
示例
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
int p=a[0]; //p=1-
int q=a[1]; //q=2-对于索引范围外的任何n,a[n]反映未定义的行为(取决于编译器)。
2)使用函数.at(index)
语法:
vector_name.at(pos_n)
参数:所需元素的索引
返回值:返回输入索引处存在的引用元素。
它返回对该元素的引用,此函数自动检查n是否在范围内。如果出现异常,则会引发超出索引范围的错误。
那就是.at()和[]运算符之间的区别,它不会使任何检查超出索引范围。
示例
//在相同的向量上
int p=a.at(0); //p=1-
int q=a.at(1); //q=2-
a.at(4) //编译错误3)front()方法
语法:
vector_name.front()
参数:无
返回值:返回向量的第一个元素的引用。
示例
//在相同的向量上
int p=a.front() //p=1-注意:在空向量上调用此函数将显示未定义的行为。
4)back()方法
语法:
vector_name.back()
参数:无
返回值:最后一个元素的引用。
示例
//在相同的向量上
int q=a.back() //q=3-注意:在空向量上调用此函数将显示未定义的行为。
C++代码演示访问向量元素的功能示例
//显示的C++程序
// how to access elements in vector in C++ STL>
#include <vector>
#include <iostream>
using namespace std;
int main( )
{
//声明向量n-
vector<int>n{1,2,3,4,5,6,7,8,9,0};
/* This is how the operator[i]
in c++ works i is the index
which is changing continuously
i.e printing the vector is best example*/
cout <<"Output of operator[]: \n";
for(int i=0; i<n.size(); i++)
cout<<n[i]<<" ";
/* This is how at() works similar
to the operator[] ,
Here it changes the whole vector
*/
cout << "\n\nOutput of at(): \n";
for(int i=0; i<n.size(); i++)
{
n.at(i)=i;
cout<<n.at(i)<<" ";
}
cout << "\n\nOutput of change vector because of at(): \n";
for(int i=0; i<n.size(); i++)
cout<<n[i]<<" ";
/*This is how the front()
works by using that here we are
accessing the front element of vector
*/
cout << "\n\nOutput of front(): \n";
cout<<n.front();
/*This is how the back()
works by using that here we are
accessing the back element of vector
*/
cout << "\n\nOutput of back(): \n";
cout<<n.back();
return 0;
}输出结果
Output of operator[]: 1 2 3 4 5 6 7 8 9 0 Output of at(): 0 1 2 3 4 5 6 7 8 9 Output of change vector because of at(): 0 1 2 3 4 5 6 7 8 9 Output of front(): 0 Output of back(): 9