I would like to sort a vector holding objects of a class with a const member variable.
Unfortunately, I get an error stating that there is "no matching function for call to "swap"".
When I remove the const keyword for id, then std::sort() works with both the overloaded operator<() and the custom compare function.
Why is this the case? Can I in general not sort objects belonging to a class with a const member variable?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct A
{
const int id;
A(int id) : id(id) {}
bool operator<(const A &other) const
{
return id < other.id;
}
};
bool cmp(const A &lhs, const A &rhs)
{
return lhs.id < rhs.id;
}
int main()
{
vector<A> vec;
vec.emplace_back(3);
vec.emplace_back(0);
vec.emplace_back(2);
vec.emplace_back(1);
std::sort(vec.begin(), vec.end());
std::sort(vec.begin(), vec.end(), cmp);
}
Ahas copy and move constructors. It's the assignment operators that are the problem forstd::swap.A(int id) : id(id) {}this is not a good idea