0

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<<" ";
    }
}
Jack G
  • 1
  • 1
  • You have the pointer `vec`, but *where does it point?* Defining a pointer variable doesn't automatically create an object that it can point to, only the pointer is created. And generally speaking, one seldom need pointers to any container, not even as arguments (use *references*). You might want to refresh some parts of your C++ text-books or invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Apr 08 '22 at 06:11

1 Answers1

1

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
schorsch_76
  • 794
  • 5
  • 19