繁体   English   中英

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

[英]Change struct member for all elements in a vector of 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 << " ";
    }
}

Output

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM