Juju
Juju

Reputation: 81

Erase duplicate of first 2 char in vector of strings

I have a vector of strings containing elements in this format : $A,1,2,3,4 I would like to erase duplicate of strings only based on the 2 first characters $A.

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

int main(){

    std::vector<std::string> vec;

    vec.push_back("$A,1,2,3,4");
    vec.push_back("$B,1,6,8,1");
    vec.push_back("$A,1,2,5,9");

    std::sort(vec.begin(), vec.end());

    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());

    for(auto &entry: vec)
        std::cout << entry << std::endl;


    return 0;
}

I want to keep only one string starting with $Ain my vector but this codes is comparing if the whole string is unique.

For example: if the string is $A...; $B...; $A...; $B... the output would be $A...; $B...

Upvotes: 2

Views: 99

Answers (1)

Jarod42
Jarod42

Reputation: 217398

Use proper predicate (compatible with the one with sort), something like:

vec.erase(std::unique(vec.begin(), vec.end(),
                      [](const std::string& lhs, const std::string& rhs){
                          return lhs.substr(0, 2) == rhs.substr(0, 2);
                      }),
          vec.end());

Upvotes: 9

Related Questions