-1

我有以下 C++ 函数:

std::vector<int> findPoss (std::vector<int>& possRow, std::vector<int>& possCol)
{
    std::vector<int> poss;
    for (int a = 0; a < 9; a++)
        for (int b = 0; b < 9; b++)
            if (possRow[a] == possCol[b])
                poss.push_back(possRow[a]);
    return poss;
}

它应该采用两个 a 向量,并返回一个包含在两个输入向量中找到的所有元素的向量。
但是,返回的向量总是包含 1。例如,如果我输入了这个:

std::vector<int> possRow;
for (int a = 0; a < 9; a++) possRow.push_back(a);
std::vector<int> possCol;
for (int b = 0; b < 9; b += 2) possCol.push_back(b);
findPoss(possow, possCol)

它会返回这个:

(0, 1, 2, 4, 6, 8)

为什么会这样?

此外,在我的findPoss函数中,没有任何内置函数可以将两个for循环合二为一,是吗?

4

3 回答 3

4
for (int b = 0; b < 9; b += 2) possCol.push_back(b);

当您在循环中使用它时将填充大小,这将possCol导致未定义[0, 2, 4, 6, 8]行为5for (int b = 0; b < 9; b++)

我建议您使用for (int b = 0; b < possCol.size(); b++)andfor (int a = 0; a < possRow.size(); a++)代替。

于 2013-04-26T19:43:16.030 回答
1

您的代码for (int b = 0; b < 9; b += 2) possCol.push_back(b);生成了一个包含五个元素的向量,但您在 possCol 上循环了九次,获得了垃圾内存。虽然你收到(0, 1, 2, 4, 6, 8)的结果很有趣。

修改该 for 循环以for (int b = 0; b < possCol.size(); b += 2)在您的 findposs 函数中读取将按预期返回 {0, 2, 4, 6, 8}。

于 2013-04-26T19:48:51.503 回答
0

基于范围的 for 循环使这变得更加清晰:

std::vector<int> findPoss (const std::vector<int>& possRow, const std::vector<int>& possCol)
{
    std::vector<int> poss;
    for (int row : possRow)
        for (int col : possCol)
            if (row == col)
                poss.push_back(row);
    return poss;
}
于 2013-04-26T21:06:49.483 回答