Thursday, 15 March 2012

C++ push_back only adds objects to position 0 in vector -



C++ push_back only adds objects to position 0 in vector -

in advance: i'm new c++, please kind. ;-)

i'm trying add together several objects (result) vector (results), somehow doesn't work way want.^^

update: changed code little , showed more code more information

//file1 class result{ public: result(string rtype, string rname, double rcosts){ type = rtype; name = rname; costs = rcosts; } private: string type, name; double costs; }; //file2 void getcosts(vector<parts> parts){ vector<part *> p; for(unsigned = 0; < parts.size(); i++){ p.push_back(&parts[i]); } cout << p.at(0)->getname() << p.at(0)->getprice << endl; //this output right cout << p.at(0)->getname() << p.at(0)->getprice << endl; //this output right cout << p.at(0)->getname() << p.at(0)->getprice << endl; //this output right vector<result *> r; for(std::vector<part *>::iterator ip = p.begin; ip != p.end(); ip++){ addresult((*ip)->gettype(), (*ip)->getname(), r, (*ip)->getprice()); } sortandprintresults(r); //after method printed results file programm ends. scope shouldn't matter. (getcosts called once) } void addresult(string type, string name, vector<result *> results, double costs){ result * res = new result(type, name, costs); results.push_back(res); cout << res->getname() << endl; //this prints name of every object }

the output should follows:

abc //results.at(0) def //results.at(1) ghi //results.at(2)

but instead it's:

abc //results.at(0) def //results.at(0) ghi //results.at(0) error: out of range. //results.at(1) error: out of range. //results.at(2)

what doing wrong?

the issue in debugging.

this code adds single, expects three.

void addresult(string type, string name, vector<result *> results, double costs){ results.push_back(new result(type, name, costs)); cout << results.at(0)->getname() << endl; cout << results.at(1)->getname() << endl; cout << results.at(2)->getname() << endl; }

you want phone call addresult 3 times before outputting.

in case, want set after forloop in getcosts:

void getcosts(vector<parts *> p){ for(std::vector<part *>::iterator ip = p.begin; ip != p.end(); ip++){ addresult((*ip)->gettype(), (*ip)->getname(), r, (*ip)->getprice()); } //check results here. }

edit: captainobvlious mentioned, you're passing vector by-value addresult function.

adding by-value means vector<result *> created locally within function, , doesn't connect r variable passed in (hence when seek r.at(0), there's nil inside)

fixing straight forward, link function-parameter results r vector, need pass by-reference, simple prepending type '&':

void addresult(string type, string name, vector<result *>& results, double costs)

have read of by-value vs by-reference.

c++ vector

No comments:

Post a Comment