提前:我是 C++ 的新手,所以请多关照。 ;-)
我正在尝试将几个对象(结果)添加到一个 vector (结果),但不知何故它无法按我想要的方式工作。^^
更新:我稍微更改了代码并显示了更多代码以获取更多信息
//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)
我做错了什么?
最佳答案
问题出在您的调试中。
此代码添加一个,然后需要三个。
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;
}
您想调用 addResult
输出前3次。
在这种情况下,您想将它放在 getCosts
中的 forloop 之后:
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.
}
编辑: 正如 CaptainObvlious 所提到的,您还将 vector 按值传递给 addResult 函数。
添加按值 表示 vector<Result *>
在函数内本地创建,不连接回 r
您传入的变量(因此当您尝试 r.at(0)
时,里面什么也没有)
修复此问题非常简单,将函数参数结果链接到您的 r
vector,您需要通过通过引用传递它,这就像在类型前面加上“&”一样简单:
void addResult(string type, string name, vector<Result *>& results, double costs)
关于C++ push_back 仅将对象添加到 vector 中的位置 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24285091/