如何在C++中删除矢量类型的重复项<string>?
How to remove duplicates of type vector<string> in C++?
我知道防止重复的一个好方法是使用unordered_set
。但是,当我想unordered_set<vector<string>>
时,这种方法似乎不起作用。我该怎么做呢?例如,我想防止<"a", "b", "c">
在我的unordered_set<vector<string>>
中重复。
这unordered_set<vector<string>>
也可以在定义的类之外使用吗?
法典:
unordered_set<vector<string>> abc({"apple", "ball", "carrot"});
abc.insert({"apple", "ball", "carrot"});
cout << abc.size() << endl; //abc.size() should be 1
有很多
方法可以消除重复项,从对象中构建集合就是其中之一。是std::set
还是std::unordered_set
由您决定,而决定通常取决于您能想出多好的哈希函数。
这反过来又需要对域的了解,例如,字符串向量代表什么以及它们可以具有什么值。 如果你确实想出了一个好的哈希,你可以像这样实现它:
struct MyHash
{
std::size_t operator()(std::vector<std::string> const& v) const
{
// your hash code here
return 0; // return your hash value instead of 0
}
};
然后,您只需使用该哈希值声明您的unordered_set
:
std::unordered_set<std::vector<std::string>, MyHash> abc;
我会说,一开始只使用std::set
是一个安全的选择,除非你有一个很好的哈希函数。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为std::string的某个索引赋值
- <<操作员在下面的行中工作
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数