c++ - 无法在 C++ 中编译 min_element

标签 c++

这是我的代码:

#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);
  }
};

这是错误:

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

我觉得有一些语法缺陷,但无法找出是哪一个。请帮忙!

最佳答案

您放置的 const 是错误的。 A T*& cannot be implicitly converted to a const T*& .尝试

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

相反。


或者只是按值传递(感谢 Mike):

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

如果编译器使用标准 ABI,这对于像指针这样的简单对象会更有效。

关于c++ - 无法在 C++ 中编译 min_element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2903804/

相关文章:

c++ - 删除 vector 中的特定值

c++ - 运行时错误问题

c++ - Python sprintf 和 memset 操作

c++ - 2 昏暗数组和双指针

c++ - asio::streambuf 优于原始数组的优势

c++ - 如何在 Qt C++ 中生成带数字签名的 PDF

c++ - 如何在文件中更新

c++ - 如何在 Qt 中序列化为 JSON

c++ - 静态短[9][9] getRandomBoard();

c++ - 无法使用 Qt 下载 >= 1GB 的文件