Checking for duplicate values associated with key in map?

I'm struggling with outputting unique values of a map<string, vector<string>> I have. Right now, I have a map, and iterate through it, with the goal of outputting only unique values associated with the specified key.

I do need to keep the duplicate values, or else I'd just remove the dups :)

After looking at this post, my set up is like the following:

 for( const auto& pair : myMap ){

        for( std::size_t i = 0; i < pair.second.size(); ++i ) {

            bool notMatch = (pair.second[i] != pair.second[i+1]){

            if (pair.first == key && notMatch){
                cout << key << " : ";
                cout << pair.second[i] << " - at index -  " << i << "\n";

I then get an output along the lines of :

"key : value - at index - 6"

"key : value - at index - 10"

My initial thought was that one of the elements might have some extra characters or something, which would make sense as to why the duplicate elements are not being seen as equal.

But when doing a simple check of -

if (pair.second[6] == pair.second[10]){
   cout << "They are equal";
} else {
   cout << "They are NOT equal";

It confirms and returns that the two elements are in fact equal. Since the elements are equal, I'm struggling to understand why bool notMatch = (pair.second[i] != pair.second[i+1]) does not consider them to be equal.

Apologies if this was posted incorrectly, I'll edit if necessary.

Thanks for your help

2 answers

  • answered 2019-03-14 10:42 julians

    Building on @Tzalumen's comment, you could insert the values in a set or unordered set and compare the size to the original vector:

    for(const auto& pair : myMap){
        unordered_set<string> s(pair.second.begin(), pair.second.end());
        if (s.size() == pair.second.size()) {
            cout << "value has unique elements" << endl;
        } else { 
            cout << "value has duplicate elements" << endl;

    If the set's size is smaller than the vector's size, you know the vector has duplicates.

  • answered 2019-03-14 10:55 Caleth

    If you don't want duplicates anywhere, why not have a std::map<std::string, std::set<std::string>> in the first place?