函数保持返回相同的值

时间:2014-12-15 00:03:16

标签: c++ vector

我的功能真的很奇怪。我正在尝试使用vector<address>x构建的结构y来循环遍历向量。大小总是已知的,没有任何东西被删除。我要做的是使用给定的xy函数应该返回存储这些值的向量元素的索引。

struct address {
    unsigned int x;
    unsigned int y;
    unsigned int n;
    address(int ax, int ay, int an): x(ax), y(ay), n(an) {}
};

查找索引的函数如下:

int find_box(vector<address> v, int x, int y, int j) {
    int xc = x;
    int yc = y;
    if(v[j].x == xc && v[j].y == yc) {
        return j;
    }
}

这就是我调用函数的方式:

for(int j = 0; j<vectorBoxes.size(); j++) {
    jot = find_box(temp->box,temp->player->x + MX[i],temp->player->y + MY[i], j);
}

在循环之前,我知道temp->player->x + MX[i] = 4和temp->player->y + MY[i] = 3。 我也知道temp->box的第一个元素[0]等于:x = 2y = 3。 我也知道元素第三元素[2]的值为x = 4y = 3。所以函数应该给我2 ...

为什么函数在第一个循环中返回0?

3 个答案:

答案 0 :(得分:1)

如果find_box函数在索引j处找不到元素,则它将返回零。这意味着当你遍历你的地址时,jot将始终设置为零,除非最后一个地址碰巧是你正在寻找的地址。

要修复它,您可以检测何时找不到匹配项,并返回一个指示此值的值,例如-1。例如,这样的事情应该有效:

int find_box(vector<address> v, int x, int y, int j) {
    if(v[j].x == x && v[j].y == y) {
        return j;
    }
    return -1;
}

for(int j = 0; j<vectorBoxes.size(); j++) {
    int tmp_jot = find_box(temp->box,temp->player->x + MX[i],temp->player->y + MY[i], j);
    if (tmp_jot >= 0) { 
        jot = tmp_jot; 
        break; 
    }
}

break语句只是为了提高效率,它会在找到匹配后立即停止for循环。没有它它会工作。这段代码可以做得更整齐,但我不想彻底改变你的逻辑。

另一个例子是,您的find_box函数可以更改为实际执行搜索并返回索引:

int find_box(vector<address> v, int x, int y) {
    for(int j = 0; j<v.size(); j++) {
        if(v[j].x == x && v[j].y == y) {
            return j;
        }
    }
    return -1;
}

jot = find_box(vectorBoxes, temp->player->x + MX[i], temp->player->y + MY[i]);

答案 1 :(得分:0)

目前,即使您可能找到了您想要的内容,您仍然会继续调用此查找功能。其次,当if语句不正确时,find_box将返回垃圾,因为您没有指定应返回的内容。

我建议(NB:作为简单修复)从该函数返回bool而不是您已经知道的值。而且你应该总是明确地返回一些东西,当你if评估为真时,你只会返回一个合理的值。

bool find_box(vector<address> v, int x, int y, int j) {
    int xc = x;
    int yc = y;
    if(v[j].x == xc && v[j].y == yc) {
        return true;
    }
    return false;
}

一旦找到了您正在寻找的东西,您也应该停止搜索,例如:

bool found = false;
for(int j = 0; j<vectorBoxes.size() && !found; j++) {
    if(find_box(temp->box,temp->player->x + MX[i],temp->player->y + MY[i], j)) {
        jot = j;
        found = true;
    }
}

答案 2 :(得分:0)

添加默认返回值以检查其是否失败

int find_box(vector<address> v, int x, int y, int j) {
    int xc = x;
    int yc = y;
    if(v[j].x == xc && v[j].y == yc) {
        return j;
    }
    return -1; // a value which you can check and ignore
}

你的problam是vectorBoxes.size()可以超过3.所以即使你在下一次迭代中找到值2,你的函数也会返回void,这是你不想要的。

myrealvalue = 0;
for(int j = 0; j<vectorBoxes.size(); j++) {
jot = find_box(temp->box,temp->player->x + MX[i],temp->player->y + MY[i], j);
if(jot == -1)
     continue;
else{
    myrealvalue = jot;
    break;
}
}    

//access real value
相关问题