在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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短