Question

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?

Was it helpful?

Solution 2

I've decided to utilize const_cast, override=, and swap to make sorting work:

template <class KEY, class VALUE>
class Wrapper {
    std::pair<const KEY, VALUE> d_data;

  public:
    Wrapper& operator=(const Wrapper &rhs) {
        const_cast<KEY&>(d_data.first) = rhs.d_data.first;
        d_data.second = rhs.d_data.second;
    }

    std::pair<const KEY, VALUE>& data() { return d_data; }
    std::pair<const KEY, VALUE> const& data() const { return d_data; }
};

template <class KEY, class VALUE>
void swap(Wrapper<KEY, VALUE>& a, Wrapper<KEY, VALUE>& b) {
    using std::swap;
    swap(const_cast<KEY&>(a.data().first), const_cast<KEY&>(b.data().first));
    swap(a.data().second, b.data().second);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top