如何检查 C++ 向量是否已包含具有特定值的元素(在本例中为结构)?

How to check if a c++ vector already contains and element with a specific value (in this case a struct)?

我需要在添加新元素之前检查具有特定值的元素是否已存在于 C++ 向量中(以避免重复)。

我检查了所有内容,这个解决方案(下面的简化代码)似乎是最有效的,如果它确实有效的话。

我遇到的问题是这一行:

"if(std::find(positions.begin(), positions.end(), pos) != positions.end())",

这让我在库中出现编译错误,说 "Invalid operands to binary expression ('position' and 'const position')"。

我知道我是 C++ 的新手,如果这是一个愚蠢的问题,我很抱歉,但是谁能告诉我我做错了什么?

值是结构体吗?它与值 vs. pointers/references 有什么关系吗(我怀疑有关系)?

struct position
{
    int column;
    int row;
};


int main ()
{
    std::vector<position> positions = {{0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}};

    position pos = {2,1};

    if(std::find(positions.begin(), positions.end(), pos) != positions.end())
    {

        positions.push_back(pos);
    }
    else
    {
        std::cout << "Value is already present" << std::endl;
    }

    return 0;
}

我很无能,真的坚持这个,这阻碍了我在我的项目中的进步。

有没有人知道我做错了什么或者我应该怎么做?

非常感谢!

这里有两处错误(可能还有其他错误,但这些是相关的)。

首先,您的结构中没有允许 find 比较项的相等运算符。这可以添加类似:

struct position {
    int column;
    int row;
    bool operator==(const position &other) const {
        return column == other.column && row == other.row;
    }
};

其次,你比较的感觉是错误的。如果 未找到 find 将 return end,因此您的 if 部分应该是:

if (std::find(positions.begin(), positions.end(), pos) == positions.end()) {
    positions.push_back(pos);
} else {
    std::cout << "Value is already present" << std::endl;
}

为了完整起见,这里有一个完整的程序,展示了当您尝试添加一个 non-existant 元素三次时会发生什么:

#include <iostream>
#include <vector>
#include <algorithm>

struct position {
    int column;
    int row;
    bool operator==(const position &other) const {
        return column == other.column && row == other.row;
    }
};

int main () {
    std::vector<position> vec = {};

    position pos = {2,1};
    for (int i = 0; i < 3; ++i) {
        if (std::find(vec.begin(), vec.end(), pos) == vec.end()) {
            std::cout << "Adding value" << std::endl;
            vec.push_back(pos);
        } else {
            std::cout << "Value is already present" << std::endl;
        }
    }

    return 0;
}

从输出中,您只能看到第一个实际插入:

Adding value
Value is already present
Value is already present