更改结构向量中所有元素的结构成员

  • 本文关键字:结构 元素 成员 向量 c++
  • 更新时间 :
  • 英文 :


这里我有一个向量"漂亮的";structs,每个都有一个简单的int成员。我只想为向量中的每个元素将结构成员更改为5,但我似乎无法使其正常工作。起初,我尝试通过地址传递向量,但结构成员没有更新。在这里,我尝试使用指针向量,但程序崩溃了,我不明白为什么这是

我已经玩了好几天了,但还是弄不明白,如果有任何帮助,我将不胜感激。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct nice{
nice(int val):v(val){}
int v;
};
void remo(vector<nice>* h){
for(nice g:*h){
g.v=5;
}
}
int main(){
vector<nice> *vec;
for(int i=0;i<7;i++){
nice n(i+1);
vec->push_back(n);
}
for(nice d:*vec){
cout<<d.v<<" ";
}
cout<<endl;
remo(vec);
for(nice d:*vec){
cout<<d.v<<" ";
}
}

我想你还不了解指针、引用和堆栈/堆。

这是代码中的一个工作示例。也许它能帮助你更好地理解这些问题。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct nice {
nice(int val) :v(val) {}
int v;
};
void remo(vector<nice>& h) {
for (nice& g : h) {
g.v = 5;
}
}
int main() {
vector<nice> vec;
for (int i = 0; i < 7; i++) {
vec.push_back({ i + 1 });
}
for (nice& d : vec) {
cout << d.v << " ";
}
cout << endl;
remo(vec);
for (nice& d : vec) {
cout << d.v << " ";
}
}

输出

1 2 3 4 5 6 7
5 5 5 5 5 5 5

最新更新