Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello, I wrote the following code to sort the map in c++ by the second value of tuples(instead of the first value). but, it gives me the error :" binary '-' : 'std::_List_iterator<_Mylist>' does not define this operator or a conversion to a type acceptable to the predefined operator" and the position of the error is in the header "algorithm.h". why does it occur?

C++
<pre>template<class T>
struct less_second
: std::binary_function<T,T,bool>
{
   inline bool operator()(const T& lhs, const T& rhs)
   {
      return lhs.second < rhs.second;
   }
};

typedef std::pair<int,int> data_t;
		std::list<data_t> vec(groups.begin(), groups.end());
		std::sort(vec.begin(), vec.end(), less_second<data_t>());


What I have tried:

I used the code from:STL std::map and sorting using value_compare - General Programming - GameDev.net[^]
Posted
Updated 8-Apr-17 4:20am
Comments
Richard MacCutchan 8-Apr-17 3:50am    
Where is the code that the error message refers to?
Member 11807654 8-Apr-17 5:16am    
it is in the algorithm header(i used #include <algorithm>) and it shows the line "_Sort(_Unchecked(_First), _Unchecked(_Last), _Last - _First, _Pred);" as the position where error occurs in. I use visual studio 2012
Richard MacCutchan 8-Apr-17 5:24am    
The algorithm code is trying to subtract one item from another, but the types declared in your template cannot use simple subtraction. So you need to define an overload for that operation.

1 solution

To sort a list, you should probably take the member function sort. See that example : list::sort - C++ Reference[^].

Generally, you won't use a std::list if you need sorting.

And if you are using a map, then the key is the field that need to be sorted. You should reconsider which containers you use and also select appropriate algorithms.
 
Share this answer
 
Comments
Richard MacCutchan 8-Apr-17 11:08am    
OP has copied some code from the internet; it may or may not be valid.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900