在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 红包祝福语简短10字
18 周六早晨祝福语简短