简体   繁体   中英

can't compile min_element in c++

This is my code:

#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class A {
  struct CompareMe {
    bool operator() (const string*& s1, const string*& s2) const { return true; }
  };
  void f() {
    CompareMe comp;
    vector<string*> v;
    min_element(v.begin(), v.end(), comp);
  }
};

And this is the error:

error: no match for call to ‘(A::CompareMe) (std::string*&, std::string*&)’
test.cpp:7: note: candidates are: bool A::CompareMe::operator()(const 
std::string*&, const std::string*&) const

I feel that there is some syntax defect, but can't find out which one. Please, help!

Your placement of const is wrong. A T*& cannot be implicitly converted to a const T*& . Try

bool operator() (const string* const& s1, const string* const& s2) const { ...
//                             ^^^^^                    ^^^^^

instead.


Or just pass by value (thanks Mike):

bool operator() (const string* s1, const string* s2) const { ...

which will be more efficient for simple objects like a pointer, if the compiler uses a standard ABI.

(This should be a comment, but a comment cannot be formatted thus, so it has to be an answer.)

The compiler's error message is very helpful. Just align what the compiler says it's expecting to what it says it's got:

(      std::string*&,       std::string*&)
(const std::string*&, const std::string*&)

Pretty obvious what's wrong, isn't it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM