| |

VerySource

 Forgot password?
 Register
Search
View: 727|Reply: 2

sort () question

[Copy link]

1

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-1-31 17:40:01
| Show all posts |Read mode
I'm using sort () to sort a sequence of classes, as follows:
#include <iostream>
#include <vector>
using namespace std;

class Test {
public:
    int _i;
    Test (int i): _i (i) {};
    bool operator <(const Test&i) const {return _i <i._i;}
};

int main ()
{
    vector <Test> v;
    for (int i = 0; i <5; i ++) {
        Test t (i);
        v.push_back (t);
    }
    sort (v.begin (), v.end ());

    for (vector <Test> :: const_iterator ci = v.begin (); ci! = v.end (); ci ++)
        cout << ci-> _ i << endl;

    return 0;
}
The above compiles without problems, but if:
 bool operator <(const Test&i) const {return _i <i._i;}
Non-constant references, or non-member functions
 bool operator <(Test&i) {return _i <i._i;}
This compile fails, and I know it's bad. But I want to know if this is a mandatory requirement of the sort function? What other library functions have similar problems?
Please advise, thank you.
Compiler version:
gcc version 3.4.5 20051201 (Red Hat 3.4.5-2)
Reply

Use magic Report

0

Threads

23

Posts

13.00

Credits

Newbie

Rank: 1

Credits
13.00

 China

Post time: 2020-3-11 16:30:02
| Show all posts
The types of objects that can be used for sorting must meet the "Less Comparable Concept", this Concept requirement
The comparison operation using <is a const operation. In this way, the result of comparison between constants or between const variables and
The comparison of two ordinary variables is the same, so both const keywords are mandatory-unless STL does not have
Meet the design requirements
Reply

Use magic Report

0

Threads

23

Posts

13.00

Credits

Newbie

Rank: 1

Credits
13.00

 China

Post time: 2020-3-11 20:30:01
| Show all posts
Regarding the reasons for this compulsory requirement, academic theory analysis is more troublesome. Simply put, you have to ensure that your
The comparison operation cannot change the state of the two operands participating in the comparison, otherwise, the result of the comparison may be the same as the previous one.
The comparison results are inconsistent, which will cause sorting confusion-so regardless of the left operand * this, or the right operand,
All have to be modified with const. When modifying * this, it is actually the const behind the parameter list.
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list