std::sort comparison object

Hi, as always I was doing an exercise and faced huge error message when I was trying to sort vector of std::pair<std::string, int> based on values of int

So I'm having this class that's supposed to act like std::map just with a poor implementation. The problem is with my void print() const; function. I want to sort all the vector pairs based on int value but I'm getting giganting error message. I dont really understand what it is about! Funny thing is that I only use this one line in that function
std::sort(vec.begin(), vec.end(), Compare{});
If I remove my print function and just randomly try to sort some random vector that I created in main it works super fine. Exactly the same line of codes gives huge error message in one place but works in another. What is going on here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <vector>
#include <string>
#include <utility>
#include <iostream>
#include <algorithm>

class Assoc{
    std::vector<std::pair<std::string, int>> vec;

public:

    int& operator[](const std::string& str);

    void print() const;
};

int& Assoc::operator [](const std::string& str)
{
    for(auto& x : vec )
    {
        if(x.first == str)
            return x.second;
    }

    vec.push_back(std::pair<std::string, int>{str, int{}});
    return vec.back().second;
}


class Compare{
public:
bool operator()(const std::pair<std::string, int>& p1, const std::pair<std::string, int>& p2){
       return p1.second < p2.second;
}
};

void Assoc::print() const
{
     std::sort(vec.begin(), vec.end(), Compare{});      //if I add this this gives huge error message
     //print sorted vec
}

int main()
{
    std::vector<std::pair<std::string, int>> vec;       //Just checking if this will give the same error        

    vec.push_back({"Hello", 1});
    vec.push_back({"World!", 2});
    
    std::sort(vec.begin(), vec.end(), Compare{});       //This works!!!!

    return 0;
}
Last edited on
It's because you have marked the print function as const.
Dude you are genius :) Thank you! I have to start spotting these things myself =[
Topic archived. No new replies allowed.