Æle*_*lex 0 c++ predicate duplicate-removal stdvector c++11
除非我遗漏了某些东西或误解了机制(很可能)不应该在这个载体中不存在"1"重复?
chunks.erase( std::unique ( chunks.begin(), chunks.end(),
[]( std::string &s1, std::string &s2 ){
return ( s1.compare(s2) == 0 ? true : false );}),
chunks.end() );
Run Code Online (Sandbox Code Playgroud)
在执行上述之前:
1 l:1
1+ l:2
1+1 l:3
1+1= l:4
+ l:1
+1 l:2
+1= l:3
1 l:1
1= l:2
= l:1
Run Code Online (Sandbox Code Playgroud)
执行上面的代码后:
1 l:1
1+ l:2
1+1 l:3
1+1= l:4
+ l:1
+1 l:2
+1= l:3
1 l:1
1= l:2
= l:1
Run Code Online (Sandbox Code Playgroud)
我试过没有谓词(假设std ::相同的字符串将被删除).出于某种原因,"那些"被认为是相同的?我已经查看了它们的长度(假设空格被卡住作为前缀或后缀),但它们具有相同的长度.
我错过了什么吗?
Mat*_* M. 12
你(可能)误解了一些东西.
std::unique只删除连续的重复项,因此如果您希望删除所有重复项,则应用的前提条件std::unique是使用相同的谓词对您的范围进行排序.
std::unique假设非唯一元素是相邻的,就像它们(例如)chunks被排序一样。这使得std::unique复杂度为 O(n)。
如果您想维护特定的顺序并删除重复项,则会出现 O(n 2vector ) 复杂度的问题。您可以使用此处提供的逻辑来执行此操作。
// Create a new vector without the duplicates\nstd::vector<string> unique_chunks;\nfor (std::vector<string>::iterator x = chunks.begin(); x != chunks.end();) {\n\xc2\xa0 if ( unique_chunks.find(*x) != unique_chunks.end() ) {\n\xc2\xa0 \xc2\xa0 unique_chunks.push_back( *x );\n\xc2\xa0 }\n}\n\n// Make chunks hold this new vector (allowing the old vector to be destroyed)\nstd::swap( chunks, unique_chunks );\nRun Code Online (Sandbox Code Playgroud)\n\n不,你不需要那个谓词。
\n