-
May 23rd, 2018, 08:02 AM
#1
[RESOLVED] vector sort
Code:
#include<vector>
#include<algorithm>
using namespace std;
class MyObj
{
public:
MyObj(int v):value(v){}
bool friend operator < (const MyObj &Ob1, const MyObj &Ob2)
{
if(Ob1.value < Ob2.value)
return true;
}
int getValue()
{
return value;
}
private:
int value;
};
int main()
{
MyObj b1 = 10;
MyObj b2 = 16;
MyObj b3 = 12;
MyObj b4 = 8;
vector <MyObj> vec2;
vec2.push_back(b1);
vec2.push_back(b2);
vec2.push_back(b3);
vec2.push_back(b4);
for( auto &i:vec2)
cout<<i.getValue() <<" ";
cout<<endl;
sort(vec2.begin(),vec2.end());
for( auto &j:vec2)
cout<<j.getValue() <<" ";
cout<<endl;
return 0;
}
i ran it in gcc the output is
$ ./a.exe
10 16 12 8
8 12 16 10
The output is wrong. But i doubt any mistake in the code. plz suggest
-
May 23rd, 2018, 08:08 AM
#2
Re: vector sort
But i doubt any mistake in the code.
But that's the only explanation!
The problem is here
Code:
bool friend operator < (const MyObj &Ob1, const MyObj &Ob2)
{
if(Ob1.value < Ob2.value)
return true;
}
What is returned if Ob1 is NOT < Ob2?
Code:
bool friend operator < (const MyObj &Ob1, const MyObj &Ob2)
{
return Ob1.value < Ob2.value;
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
May 23rd, 2018, 08:17 AM
#3
Re: vector sort
Thanks for quick suggestion. It worked
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|