When we are compiling the below code using g++ in debian machine, then following errors are generated...can anyone pls help me why the error are? I tried by commenting sort line then error dissappears however our task requires sorting to be done then what can be the possible solution
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Here is a simple struct
struct MyStruct
{
int Num;
// Define the operator <
bool operator <(const MyStruct& Rhs)
{
return (Num < Rhs.Num);
}
};
int main()
{
vector<MyStruct> MyVector;
// Let the size be 5.
MyVector.resize(5);
// Push 5 instances of MyStruct with Num ranging
// from 5 to 1
MyStruct TestStruct;
int i = 0;
for (i = 0; i < 5; ++i)
{
TestStruct.Num = 5 - i;
MyVector[i] = TestStruct;
}
// Now sort the vector
sort(MyVector.begin(), MyVector.end());
// Try to display Num for each element. It is sorted
for (i = 0; i < 5; ++i)
{
cout << MyVector[i].Num << '\n';
}
return 0;
}
Output:
In file included from /usr/include/c++/4.7/algorithm:63:0, from 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 from ‘_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 from ‘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 from ‘void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator >]’ testvect.cpp:33:41: required from here /usr/include/c++/4.7/bits/stl_algo.h:2271:4: error: passing ‘const MyStruct’ as ‘this’ argument of ‘bool MyStruct::operator<(const MyStruct&)’ discards qualifiers [-fpermissive]
const
. It should help. – Revolver_Ocelot-std=c++14 -O2 -Wall
and added @Revolver_Ocelot's const suggestion, without error. Link – RobClucas