vendredi 14 août 2020

Map when sorted in c++ produces huge error

I am new to using maps, and when I try to sort it using the code below

#include <iostream>
#include<map>
#include<algorithm>
using namespace std;

int main()
{
    map<int,int> mp;
    mp[2]++;
    mp[5]++;
    mp[1]++;
    sort(mp.begin(), mp.end());
}

An error is thrown:

In file included from /usr/include/c++/6/algorithm:62:0,
                 from main.cpp:11:
/usr/include/c++/6/bits/stl_algo.h: In instantiation of ‘void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_Rb_tree_iterator<std::pair<const int, int> >; _Compare = __gnu_cxx::__ops::_Iter_less_iter]’:
/usr/include/c++/6/bits/stl_algo.h:4707:18:   required from ‘void std::sort(_RAIter, _RAIter) [with _RAIter = std::_Rb_tree_iterator<std::pair<const int, int> >]’
<span class="error_line" onclick="ide.gotoLine('main.cpp',21)">main.cpp:21:30</span>:   required from here
/usr/include/c++/6/bits/stl_algo.h:1966:22: error: no match for ‘operator-’ (operand types are ‘std::_Rb_tree_iterator >’ and ‘std::_Rb_tree_iterator >’)
     std::__lg(__last - __first) * 2,
               ~~~~~~~^~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:67:0,
                 from /usr/include/c++/6/bits/char_traits.h:39,
                 from /usr/include/c++/6/ios:40,
                 from /usr/include/c++/6/ostream:38,
                 from /usr/include/c++/6/iostream:39,
                 from main.cpp:9:
/usr/include/c++/6/bits/stl_iterator.h:336:5: note: candidate: template decltype ((__x.base() - __y.base())) std::operator-(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
     operator-(const reverse_iterator<_Iterator>& __x,
     ^~~~~~~~
/usr/include/c++/6/bits/stl_iterator.h:336:5: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/6/algorithm:62:0,
                 from main.cpp:11:
/usr/include/c++/6/bits/stl_algo.h:1966:22: note:   ‘std::_Rb_tree_iterator >’ is not derived from ‘const std::reverse_iterator<_Iterator>’
     std::__lg(__last - __first) * 2,
               ~~~~~~~^~~~~~~~~

What might be the problem? I have tried changing the code in different ways, but to no avail. I dont seem to find the small mistake I have made in the code

Aucun commentaire:

Enregistrer un commentaire