提前:我是C++的新手,所以請客氣一點。 ;-)C++ push_back僅將向量中的對象添加到向量中的位置0
我想幾個對象(結果)添加到載體(結果),但不知何故,它不工作的方式我想^^
更新:我改變了代碼小而表現出一些更多的代碼以獲取更多信息
//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
}
輸出應該如下:
abc //results.at(0)
def //results.at(1)
ghi //results.at(2)
但是,相反它是:
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)
我在做什麼錯?
什麼是'r'在'getCosts'? – dyp
請嘗試創建一個[最小可編譯示例](http://stackoverflow.com/help/mcve)。 – dyp
'vector'通過'new'加插入元素被認爲是不好的做法(因爲它容易出錯並且效率低下)。如果可能,只需使用'vector ';否則'vector >' –
dyp