使用函数c ++更新数组

时间:2015-01-13 01:44:57

标签: c++ arrays

我有一个非常无聊的问题。

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
}

nodestruct。它有向量concitycostcity。当我调用此函数来更新main中的值时,它不起作用!当我打印出来时,它仍然显示相同的旧值......

3 个答案:

答案 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

http://clc-wiki.net/wiki/C_language:Terms:Pass_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) {