在C ++ STL中更改向量的特定元素
给定一个C++STL向量,我们必须更改一个特定元素。
更改向量的特定元素
我们可以使用以下方式更改C++STL向量的特定元素
使用vector::at()函数
并且,使用vector::operator[]
注意:要使用vector–包含<vector>头文件,并使用vector::at()函数和vector::operator[]–包含<algorithm>头文件,或者我们可以简单地使用<bits/stdc++。h>头文件。
C++STL程序,用于更改向量的元素
//C++STL程序更改矢量的元素 #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v1{ 10, 20, 30, 40, 50 }; //打印元素 cout << "vector elements before the change..." << endl; for (int x : v1) cout << x << " "; cout << endl; //更改索引1处的元素 v1.at(1) = 100; //更改索引2处的元素 v1[2] = 200; //打印元素 cout << "vector elements after the change..." << endl; for (int x : v1) cout << x << " "; cout << endl; return 0; }
输出结果
vector elements before the change... 10 20 30 40 50 vector elements after the change... 10 100 200 40 50