[英]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.