[英]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())”,
这给了我库内部编译错误,说“二进制表达式的无效操作数('position'和'const position')”。
我知道我是C ++的新手,如果这是一个愚蠢的问题,我感到抱歉,但是有人可以告诉我我在做什么错吗?
值是结构的事实吗? 它与值与指针/引用有关系吗(我怀疑是这样)?
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
将返回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;
}
为了完整起见,这是一个完整的程序,该程序显示了当您尝试三次添加不存在的元素时发生的情况:
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.