从std :: vector <std :: string> </std :: string>中删除不区分大小写的复制

时间:2013-12-31 10:03:09

标签: sorting c++11 stdvector erase

这很奇怪,无法erasestd::vector删除不区分大小写的重复内容?有人可以让我知道如何实现这一目标吗?这是我的代码:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> stringVec = {"John", "Bob", "Joe", "Zack", "Randy", "bob", "joe", "andy"};
    sort(stringVec.begin(), stringVec.end());
    stringVec.erase(unique(stringVec.begin(), stringVec.end()),stringVec.end());

    for(unsigned i=0; i<stringVec.size(); i++)
    {
        cout<<stringVec[i]<<endl;
    }

    return 0;
}

上述代码的输出:

Success time: 0 memory: 3432 signal:0
Bob
Joe
John
Randy
Zack
andy
bob
joe

我希望至少删除joebob并将andy放在第一个索引中。

1 个答案:

答案 0 :(得分:1)

您可以通过将不区分大小写的谓词传递给sort()unique()来解决此问题:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

string lowercase(string x)
{
  transform(x.begin(), x.end(), x.begin(), [](char x) { return tolower(x); });
  return x;
}


int main()
{
    vector<string> stringVec = {"John", "Bob", "Joe", "Zack", "Randy", "bob", "joe", "andy"};
    sort(stringVec.begin(), stringVec.end(),
      [](const string &a, const string &b) { return lowercase(a) < lowercase(b); }
    );
    stringVec.erase(
      unique(stringVec.begin(), stringVec.end(),
        [](const string &a, const string &b) { return lowercase(a) == lowercase(b); }
      ),
      stringVec.end()
    );

    for(unsigned i=0; i<stringVec.size(); i++)
    {
        cout<<stringVec[i]<<endl;
    }

    return 0;
}

Live example

相关问题