Jack G
Jack G

Reputation: 1

Change struct member for all elements in a vector of structs

Here I have a vector of "nice" structs, each with a simple int member. All i want to do is for each element in the vector change the struct member to 5, but i cant seem to get it to behave properly. i tried at first passing the vector by address but the struct members didnt update. Here i tried using a pointer vector but the program crashes and i cant figure out why that is either

Ive been playing with this for several days but cant figure it out, any help would be appreciated.

#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<<" ";
    }
}

Upvotes: 0

Views: 372

Answers (1)

schorsch_76
schorsch_76

Reputation: 862

i guess you dont understand yet pointers, references and stack/heap.

This is a working example from your code. Maybe it helps you to better understand this issues.

#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

Upvotes: 1

Related Questions