C++ 使用 std::set 删除结构的重复项失败。

标签 c++ duplicates set

当我尝试删除 std::vector 中的重复结构项时遇到问题。 首先我定义一个结构。

typedef unsigned int       uint32_t;

struct TokenTerm{
std::string     value;
std::string     type;
uint32_t        start_pos;
uint32_t        end_pos;
}

然后经过几个过程我得到了一个 vector 。我定义了 op :

struct equal4EntityTermSet
{
bool operator()(const TokenTerm&l_term, const TokenTerm&r_term)
{       
        if (l_term.type == r_term.type and l_term.norm_value == 
            r_term.norm_value and l_term.start_pos == r_term.start_pos
            and l_term.end_pos == r_term.end_pos )
        {
            return false;
        }
        return true;
    }
};

接下来,我尝试通过插入集合中的每个项目来删除重复的 TokenTerm。

for(it = _query_term.m_entities.begin();it!= _query_term.m_entities.end(); it++)
{
    entSet.insert(*it);
}

_query_term.m_entities.clear();

for(itSet = entSet.begin(); itSet!=entSet.end(); itSet++)
{
    _query_term.m_entities.push_back(*itSet);
}

最后,它说的是部分内容。我删除了相同的重复项目。但它仍然存在重复。然后我打印这些项目,它们与其他项目完全相同(我比较它并打印 bool 值)

希望有帮助。

最佳答案

std::set 通过三分法检测重复项,该定律规定如果 !cmp(a, b) && !cmp(b, a) then eq(a, b),对于某些顺序关系 cmp 和某些等价关系 eq。如果您希望 eq 代表相等,则需要提供一个顺序关系 cmp 来模拟 TokenTerm< 之间的严格总排序/s。其中一种排序是字典顺序,可以通过 std::tie 轻松实现。这是一个完整的示例:

#include <set>
#include <tuple>
#include <string>
#include <iostream>

typedef unsigned int uint32_t;

struct TokenTerm {
    std::string     value;
    std::string     type;
    uint32_t        start_pos;
    uint32_t        end_pos;
};

struct TokenTermCmp {
    bool operator()(TokenTerm const& x, TokenTerm const& y) const {
        return std::tie(x.value, x.type, x.start_pos, x.end_pos) < std::tie(y.value, y.type, y.start_pos, y.end_pos);
    }
};

int main() {
    std::set<TokenTerm, TokenTermCmp> tokens;
    tokens.insert({"value", "type", 0, 10});
    tokens.insert({"value", "type", 0, 10});

    for (auto&& token: tokens) 
        std::cout << token.value << ", "
                  << token.type << ", "
                  << token.start_pos << ", "         
                  << token.end_pos
                  << '\n';
}

在上面,尽管两次插入了值 {"value", "type", 0, 10}TokenTerm,该集合仍然包含一个元素。希望这能解决问题。

关于C++ 使用 std::set 删除结构的重复项失败。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53114269/

相关文章:

c++ - 用 RBGA 值填充枚举

c++ - 输出 cout 是感叹号。 C++

c++ - 从索引的任一侧增加值来查找数组中的最大值

c++ - 如何在 wchar_t* 数组中查找文本

Java-如何在ArrayList中的重复字符串中查找字符串中的字母

java - linkedhashmap 的重复项

java - 如何使用 EL 避免重复?

java - 我是否需要重写类 <A> 的 equals 方法才能获取 Set<A> 中的唯一对象?

java - 如何创建一个包含未知数量对象的变量?

object - 无边框线的 Gnuplot png 文件