错误:分配只读引用'__b'

时间:2016-07-16 10:55:13

标签: c++ vector swap

void customsort()
{
    int a = 0;
    int b = 0;
    vector<pair<int, int> >::const_iterator it1,it2;
    for(it1 = temp.begin();it1<temp.end();it1++)
        for(it2 = temp.begin()+1;it2<temp.end();it2++)
            {
                a = it1->first+it1->second;
                b = it2->first+it2->second;     
                if(a>b)
                {   
                    swap(it1->first, it2->first);
                    swap(it1->second, it2->second);
                }
            }   
}

这是代码

我要做的是交换配对的载体

例如

说我有[1,1],[1,2],[2,0],[3,2]

我想根据它们的总和(升序)对它们进行排序

BUT 我收到了错误

In file included from /usr/include/c++/4.8/bits/stl_pair.h:59:0,
                 from /usr/include/c++/4.8/bits/stl_algobase.h:64,
                 from /usr/include/c++/4.8/bits/char_traits.h:39,
                 from /usr/include/c++/4.8/ios:40,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from prog1.cpp:1:
/usr/include/c++/4.8/bits/move.h: In instantiation of ‘void std::swap(_Tp&, _Tp&) [with _Tp = const int]’:
prog1.cpp:23:34:   required from here
/usr/include/c++/4.8/bits/move.h:176:11: error: assignment of read-only reference ‘__a’
       __a = _GLIBCXX_MOVE(__b);
           ^
/usr/include/c++/4.8/bits/move.h:177:11: error: assignment of read-only reference ‘__b’
       __b = _GLIBCXX_MOVE(__tmp);

先谢谢

2 个答案:

答案 0 :(得分:0)

对变量iteratorconst_iterator使用it1而不是it2

无法使用const_iterator更改值(并且swap想要更改值),这就是您收到错误的原因。

答案 1 :(得分:0)

错误消息显示:

In instantiation of ‘void std::swap(_Tp&, _Tp&) [with _Tp = const int]’:

即。它认为你试图交换两个const int,这是不可能的。 intconst的原因是您使用的是const_iterator而不是iterator