将std::swap_range与std::map一起使用



我想使用标准算法交换两个映射的部分,但不知何故,映射上的迭代器似乎无法交换。我肯定错过了什么。

示例

#include<map>
#include<algorithm>
auto function(std::map<int,int> m1, std::map<int,int> m2)
{
auto first = m1.begin();
auto last = first;
std::advance(last, 3);
std::swap_ranges(first, last, m2.begin());
}

错误

请在编译器资源管理器上查看:https://godbolt.org/z/6bn1xYTTr

In file included from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_tree.h:63,
from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/map:60,
from <source>:1:
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h: In instantiation of 'void std::iter_swap(_ForwardIterator1, _ForwardIterator2) [with _ForwardIterator1 = _Rb_tree_iterator<pair<const int, int> >; _ForwardIterator2 = _Rb_tree_iterator<pair<const int, int> >]':
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h:212:16:   required from '_ForwardIterator2 std::swap_ranges(_ForwardIterator1, _ForwardIterator1, _ForwardIterator2) [with _ForwardIterator1 = _Rb_tree_iterator<pair<const int, int> >; _ForwardIterator2 = _Rb_tree_iterator<pair<const int, int> >]'
<source>:9:21:   required from here
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h:182:11: error: use of deleted function 'typename std::enable_if<(! std::__and_<std::__is_swappable<_T1>, std::__is_swappable<_T2> >::value)>::type std::swap(pair<_T1, _T2>&, pair<_T1, _T2>&) [with _T1 = const int; _T2 = int; typename enable_if<(! __and_<__is_swappable<_T1>, __is_swappable<_T2> >::value)>::type = void]'
182 |       swap(*__a, *__b);
|       ~~~~^~~~~~~~~~~~
In file included from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h:64:
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_pair.h:715:5: note: declared here
715 |     swap(pair<_T1, _T2>&, pair<_T1, _T2>&) = delete;
|     ^~~~
Compiler returned: 1

std::map被实现为某种二进制搜索树,其结构取决于每个项的键永远不会改变。因此CCD_ 2返回的类型为CCD_。注意,第一intconst。你不能修改它。

std::swap_ranges试图将第一范围的每个元素与其在第二范围中的对应元素交换,但是由于它们的第一元素的const性质,std::pair<const int, int>s不能被swapped。

最新更新