'operator>'에는 const가 필요하지만 'operator <'에는 왜 필요하지 않습니까?
다음 코드를 고려하십시오.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator < (const MyStruct& other) {
return (key < other.key);
}
};
int main() {
std::vector < MyStruct > vec;
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
std::sort(vec.begin(), vec.end());
for (const MyStruct& a : vec) {
cout << a.key << ": " << a.stringValue << endl;
}
}
잘 컴파일되고 예상되는 출력을 제공합니다. 그러나 구조를 내림차순으로 정렬하려고하면 :
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator > (const MyStruct& other) {
return (key > other.key);
}
};
int main() {
std::vector < MyStruct > vec;
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
std::sort(vec.begin(), vec.end(), greater<MyStruct>());
for (const MyStruct& a : vec) {
cout << a.key << ": " << a.stringValue << endl;
}
}
이것은 나에게 오류를 준다. 다음은 전체 메시지입니다 .
/usr/include/c++/7.2.0/bits/stl_function.h : 'constexpr bool std :: greater <_Tp> :: operator () (const _Tp &, const _Tp &) const [with _Tp = MyStruct]'인스턴스화 중 :
/usr/include/c++/7.2.0/bits/stl_function.h:376:20 : error : no match for 'operator>'(operand types are 'const MyStruct'and 'const MyStruct')
{return __x> __y ; }
바로 여기에있는이 함수에는 const
한정자 가 없기 때문인 것 같습니다 .
bool operator > (const MyStruct& other) {
return (key > other.key);
}
추가하면
bool operator > (const MyStruct& other) const {
return (key > other.key);
}
Then everything is fine again. Why is this so? I'm not too familiar with operator overloading, so I've just put it in memory that we need to add the const
but it's still weird why it works for operator<
without the const
.
You get different behaviors because you are in fact calling two different (overloaded) sort functions.
In the first case you call the two parameter std::sort
, which uses operator<
directly. Since the iterators to your vector elements produce non-const references, it can apply operator<
just fine.
In the second case, you are using the three parameter version of std::sort
. The one that accepts a functor. You pass std::greater
. And that functor has an operator()
declared as follows:
constexpr bool operator()( const T& lhs, const T& rhs ) const;
Note the const references. It binds the elements it needs to compare to const references. So your own operator>
must be const correct as well.
If you were to call std::sort
with std::less
, your operator<
will produce the same error, because it's not const-correct.
Use of std::sort(vec.begin(), vec.end())
depends only on the operator<
function. It does not require that the function be able to work with const
objects.
std::greater
, on the other hand, requires the function be able to work with const
objects.
You will see a similar problem if you use std::less
, such as std::sort(vec.begin(), vec.end(), std::less<MyStruct>())
.
Having said that, there is no reason for the operator<
function and the operator>
function to be non-const
member functions. Any member function that does not modify member data should be made a const
member function.
ReferenceURL : https://stackoverflow.com/questions/48878629/why-is-const-required-for-operator-but-not-for-operator
'Nice programing' 카테고리의 다른 글
업로드하기 전에 이미지의 크기를 확인할 수 있습니까? (0) | 2020.12.29 |
---|---|
임의 길이 문자열의 numpy 배열을 만드는 방법은 무엇입니까? (0) | 2020.12.29 |
Android에서 다른 조각으로 이동 한 후 탐색 스택을 지우는 방법 (0) | 2020.12.29 |
통계를 위해 인간 방문자와 구분하여 봇에게 알려주시겠습니까? (0) | 2020.12.28 |
Java에서 최대 날짜 값을 얻는 가장 좋은 방법은 무엇입니까? (0) | 2020.12.28 |