c++ - Error is generated with the sort method while sorting the values inside a vector -
when compiling below code using g++ in debian machine, following errors generated...can pls me why error are? tried commenting sort line error dissappears our task requires sorting done can possible solution
code:
#include <iostream> #include <vector> #include <algorithm> using namespace std; // here simple struct struct mystruct { int num; // define operator < bool operator <(const mystruct& rhs) { return (num < rhs.num); } }; int main() { vector<mystruct> myvector; // let size 5. myvector.resize(5); // push 5 instances of mystruct num ranging // 5 1 mystruct teststruct; int = 0; (i = 0; < 5; ++i) { teststruct.num = 5 - i; myvector[i] = teststruct; } // sort vector sort(myvector.begin(), myvector.end()); // try display num each element. sorted (i = 0; < 5; ++i) { cout << myvector[i].num << '\n'; } return 0;
}
output:
in file included /usr/include/c++/4.7/algorithm:63:0, testvect.cpp:3: /usr/include/c++/4.7/bits/stl_algo.h: in instantiation of ‘_randomaccessiterator std::__unguarded_partition(_randomaccessiterator, _randomaccessiterator, const _tp&) [with _randomaccessiterator = __gnu_cxx::__normal_iterator >; _tp = mystruct]’: /usr/include/c++/4.7/bits/stl_algo.h:2309:70: required ‘_randomaccessiterator std::__unguarded_partition_pivot(_randomaccessiterator, _randomaccessiterator) [with _randomaccessiterator = __gnu_cxx::__normal_iterator >]’ /usr/include/c++/4.7/bits/stl_algo.h:2340:54: required ‘void std::__introsort_loop(_randomaccessiterator, _randomaccessiterator, _size) [with _randomaccessiterator = __gnu_cxx::__normal_iterator >; _size = int]’ /usr/include/c++/4.7/bits/stl_algo.h:5476:4: required ‘void std::sort(_raiter, _raiter) [with _raiter = __gnu_cxx::__normal_iterator >]’ testvect.cpp:33:41: required here /usr/include/c++/4.7/bits/stl_algo.h:2271:4: error: passing ‘const mystruct’ ‘this’ argument of ‘bool mystruct::operator<(const mystruct&)’ discards qualifiers [-fpermissive]
you use quite dated compiler stl used const& parameters, in more modern versions passed rvalue references , not require const operator<, fix it:
change:
bool operator <(const mystruct& rhs)
to
bool operator <(const mystruct& rhs) const ^^^^^
alternately, use later version of compiler supports more modern versions of c++ , enable more modern versions '-std=c++11' or '-std=c++14'.
Comments
Post a Comment