从 vector<vector> 中删除重复值<string>,不区分大小写? C++



嗨,我试图从我的向量中删除重复的值。它被建立成一个向量。这个向量包含一个向量列表,在每个内部向量中有3个字符串。

我试着:

removeCopies.erase( unique(removeCopies.begin(), removeCopies.end() ), removeCopies.end());

但是它仍然在内部向量中留下一些字符串,比如:

mainVector: {
interiorVector1: string 1: "book", string 2: "noun", string3: "A book"
interiorVector2: string 1: "book", string 2: "noun", string3: "a BOok"
}

我也不能把它全部改成小写,我不能编辑向量里面的值

如果你需要一个更好的解释,请问。谢谢你。

编辑:

我试着

unique(stringVec.begin(), stringVec.end(), [](const string &a, const string 
&b) { return lowercase(a) == lowercase(b); }), stringVec.end()

,其中小写()将整个字符串变为小写。但是它不允许我访问内部的向量字符串来做这个。

就像std::sort一样,std::unique接受BinaryPredicate,在unique的情况下用于相等比较:

template< class ForwardIt, class BinaryPredicate >
constexpr ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p );

如果您提供不区分大小写的谓词,那么它应该工作得很好。如果你不想重新发明轮子,我推荐boost::iequals

下面的代码不适用于特定的嵌套向量示例,但是如果在向量中只有字符串,则生成的代码将看起来像这样:

removeCopies.erase(std::unique(begin(removeCopies), end(removeCopies), boost::iequals), end(removeCopies));

在您的情况下,您可能想要编写一个自定义lambda,它在内部使用iequals来执行元素明智的比较。

编辑:这是iequals的折扣版本:

bool iequals(const std::string& lhs, const std::string& rhs)
{
if (lhs.size() != rhs.size())
return false;
for(size_t i = 0; i < lhs.size(); ++i)
{
if (std::tolower(lhs[i]) != std::tolower(rhs[i]))
return false;
}
return true;
}

最新更新