-
Sorting STL vector
How do I sort a STL vector containing my own class.
I have a class called CObject and a vector
vector<CObject> Objects
In CObject is a function called GetYPos().
I need to sort the vector so that the Objects with the lowest YPos are first.
I tried using std::sort with the operator < overloaded in CObject but it doesn't work.
Is there any other solutions?
Thanks
-
The overloaded operator < and std::sort method is the easiest. What kind of errors were you getting?
-
Code:
#include <iostream>
#include <vector>
#include <algorithm>
class MyObject
{
int m_x;
public:
MyObject& operator=(int x)
{
m_x = x;
return *this;
}
bool operator<(const MyObject& rhs)
{
return (m_x < rhs.m_x);
}
void Print()
{
std::cout << m_x << " ";
}
};
int main(void)
{
std::vector<MyObject> vec(4);
int i;
vec[0] = 8;
vec[1] = 5;
vec[2] = 0;
vec[3] = 2;
for(i = 0;i < vec.size();++i)
{
vec[i].Print();
}
std::cout << std::endl;
std::sort(vec.begin(),vec.end());
for(i = 0;i < vec.size();++i)
{
vec[i].Print();
}
std::cout << std::endl;
return 0;
}
-
passing `const CObject' as `this' argument of `bool CObject::operator<(const CObject&)' discards qualifiers
stl_algo.h:2118: instantiated from `void std::__introsort_loop(_RandomAccessIter, _RandomAccessIter, _Size) [with _RandomAccessIter = __gnu_cxx::__normal_iterator< CObject*, std::vector< CObject, std::allocator< CObject> > >, _Size = int]'
-
First off, does your overloaded < operator work outside of the sort function like if you just tested it in main?
-
-
Hmmmm.... post the relevant code, that might help.
-
The member function must be const.
It should look like this.
Code:
bool CObject::operator<(const CObject&) const
My second post on the following thread answers a very similiar question, and shows why the function signature looks like it does.
http://www.cprogramming.com/cboard/s...const+operator