c++ - for_each pointer in a vector of pointers -


i'd initialize vector of pointers in for_each() function:

#include <stdlib.h> #include <vector> #include <iostream> #include <algorithm> using namespace std;  class cow{         public:                 cow(){ _age = rand()% 20; }                 int get_age() { return _age;}         private:                 int _age; };  void add_new(cow* cowp) {         cowp = new cow; }  int main() {         srand(time(null));         const int herd_size=10;         vector<cow*> herd(herd_size);         for_each(herd.begin(), herd.end(),add_new);         cout << "age: " << herd[0]->get_age() << endl; // line 27 } 

however, runtime "segmentation fault" error @ line 27. herd vector seems uninitizlized. why?

your function takes pointers in value, reassigns copies. need take them in reference in order affect pointers in vector.

void add_new(cow *& cowp)  

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -