簡體   English   中英

在C ++中使用向量的函數

[英]Function using vectors in C++

我有以下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;
}

其中應有兩個向量,並返回一個向量,其中包含在兩個輸入向量中都找到的所有元素。
但是,返回向量始終包含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循環都包含在其中,是嗎?

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

for (int b = 0; b < 9; b++)循環中使用possColpossCol使用大小為5 [0, 2, 4, 6, 8] possCol填充possCol ,這將導致不確定的行為

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

for (int b = 0; b < 9; b += 2) possCol.push_back(b); 產生一個包含五個元素的向量,但是您在possCol上循環了九次,從而獲得了垃圾內存。 雖然很有趣,但是您收到的結果卻是(0, 1, 2, 4, 6, 8)

在findposs函數中修改要讀取的for循環for (int b = 0; b < possCol.size(); b += 2)將按預期返回{0,2,4,6,8}。

基於范圍的循環使這一大堆清潔:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM