In advance: I'm new to C++, so please be kind. ;-)
I'm trying to add several Objects (Result) to a vector (results), but somehow it doesn't work the way i want.^^
UPDATE: I changed the code a little and showed some more code for 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 i = 0; i < parts.size(); i++){
p.push_back(&parts[i]);
}
cout << p.at(0)->getName() << p.at(0)->getPrice << endl; //this output is correct
cout << p.at(0)->getName() << p.at(0)->getPrice << endl; //this output is correct
cout << p.at(0)->getName() << p.at(0)->getPrice << endl; //this output is correct
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 this method printed the results into a file the programm ends. so the scope shouldn't matter. (getCosts is only 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 the name of every object
}
The output should be as 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 am i doing wrong?