我有一个非常无聊的问题。
void update(node city, int costpath) {
int i;
for (i = 1; i < city.concity.size(); i++) {
city.costcity[i] = city.costcity[i] + costpath;
}
// Updates the sorrounding paths with the cost path of the previous one
}
node
是struct
。它有向量concity
和costcity
。当我调用此函数来更新main中的值时,它不起作用!当我打印出来时,它仍然显示相同的旧值......
答案 0 :(得分:4)
两个问题:
void update(node city, int costpath) {
// ^^^^ 1) You're taking your node by-value. So it's a copy
// Internal to this function, you're just modifying the local city
int i;
for (i=1;i<city.concity.size();i++) {
// ^^^ 2) C++ is zero-indexed, so this loop skips the first element
正确的实施方式是:
void update(node& city, int costpath) {
for (int i = 0; i < city.concity.size(); ++i) {
city.costcity[i] += costpath;
}
}
答案 1 :(得分:0)
C和C ++在调用函数时按值传递参数。
void update(node* city, int costpath) {
int i;
for (i=1;i<city->concity.size();i++) {
city->costcity[i] = city->costcity[i] + costpath;
}
}
请参阅http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value
答案 2 :(得分:0)
传递node city
作为函数的指针或引用。
c ++被0
索引,因此从0
开始并递增到数组大小。
void update(node& city, int costpath) {
或
void update(node* city, int costpath) {
和
for (int i = 0; i < city.concity.size(); ++i) {