I have a vector set up like this and I want to sort it:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
const int a =10;
int b = 20;
pair<const int, int> constPair1(a,b);
b=30;
pair<const int, int> constPair2(a,b);
vector<pair<const int, int>> vec{constPair1,constPair2};
sort(vec.begin(),vec.end());
return 0;
}
Unfortunately the sort above will not compile because of the const values. Is there any way I can sort this vector? Or am I stuck creating a new vector and copying values over?
In C++03, elements in a std::vector have to be copy-assignable and copy-constructible in c++. A pair with a const member does not meet that requirement and is thus invalid. The compiler is right to recject it.
In C++11, elements in a std::vector have to be move-assignable and move-constructible. A pair with a const member cannot be moved and will thus result in invalid code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With