在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 好听的元旦简短祝福语