I encountered a problem while compiling a C++ program which contains a built-in template function sort(). The source of the whole trouble is the statement as follows:
sort(Int.begin(),Int.end());
where Int is a vector containing objects of a class which overloaded the operator<().
My program can be compiled with xlC_r successfully. So I want to know whether gcc doesn't completely support template function or there are some switches I didn't turn on. The whole code is as follows:
//------code begins----------------- #include <iostream> #include <vector> #include <algorithm>
using namespace std;
class Integer{ public: int i; Integer(int ii):i(ii){} bool operator<(Integer& other) {return this->i < other.i;} };
int main() { vector<Integer> Int; Int.push_back(Integer(5)); Int.push_back(Integer(15)); Int.push_back(Integer(0));
sort(Int.begin(),Int.end()); // the source of trouble
for(int k=0; k<Int.size();k++) cout<<Int[k].i<<endl; } //---------code ends--------------
The error messages I got were like this:
/usr/local/include/c++/3.3.3/bits/stl_algo.h: In function `const _Tp&
std::__median(const _Tp&, const _Tp&, const _Tp&) [with _Tp = Integer]':
/usr/local/include/c++/3.3.3/bits/stl_algo.h:2120: instantiated from `void std::__introsort_loop(_RandomAccessIter, _RandomAccessIter, _Size) [with _RandomAccessIter = __gnu_cxx::__normal_iterator<Integer*, std::vector<Integer, std::allocator<Integer> > >, _Size = long int]'
/usr/local/include/c++/3.3.3/bits/stl_algo.h:2180: instantiated from `void std::sort(_RandomAccessIter, _RandomAccessIter) [with _RandomAccessIter = __gnu_cxx::__normal_iterator<Integer*, std::vector<Integer, std::allocator<Integer> > >]'main.cpp:21: instantiated from here
/usr/local/include/c++/3.3.3/bits/stl_algo.h:90: error: no match for 'operator<
' in '__a < __b'
... ...
Could any of you tell me what causes the failure of the compilation and how to fix it?
Any suggestions or hints will be appreciated!
Thanks in advance!
Jinming Xu
_________________________________________________________________
Learn to simplify your finances and your life in Streamline Your Life from MSN Money. http://special.msn.com/money/0405streamline.armx