如何对包含const值的向量进行排序 [英] How to sort a vector containing const values

查看:48
本文介绍了如何对包含const值的向量进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个矢量,我想对它进行排序:

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;
}

不幸的是,由于const值,上面的排序无法编译.有什么办法可以对这个向量进行排序吗?还是我坚持创建一个新向量并复制值?

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?

推荐答案

我决定使用const_castoverride=swap进行排序:

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);
}

这篇关于如何对包含const值的向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆