在 C++ 中打印对向量
Printing vector of pair in C++
这里是打印向量对值的代码
但是为什么它会打印下面提到的输出..?
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<pair<int,int>>vec(3,pair<int,int>()); // declaring the vector of pair.
for(auto x: vec)
x=make_pair(1,2); // looping through it to insert values
for(auto x:vec)
cout<<x.first<<" "<<x.second<<endl; // printing it
return 0;
}
输出:
0 0
0 0
0 0
预期:
1 2
1 2
1 2
在您的第一个 for 循环中,您“按值”遍历向量,这意味着您将元素复制到 auto x
,然后将 x 设置为 {1,2}
,这不会更改您的原始向量.要实际更改您的向量,您必须通过引用遍历它:
for(auto& x: vec)
x=make_pair(1,2);
这里是打印向量对值的代码
但是为什么它会打印下面提到的输出..?
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<pair<int,int>>vec(3,pair<int,int>()); // declaring the vector of pair.
for(auto x: vec)
x=make_pair(1,2); // looping through it to insert values
for(auto x:vec)
cout<<x.first<<" "<<x.second<<endl; // printing it
return 0;
}
输出:
0 0
0 0
0 0
预期:
1 2
1 2
1 2
在您的第一个 for 循环中,您“按值”遍历向量,这意味着您将元素复制到 auto x
,然后将 x 设置为 {1,2}
,这不会更改您的原始向量.要实际更改您的向量,您必须通过引用遍历它:
for(auto& x: vec)
x=make_pair(1,2);