sort() - 没有用于调用'swap'的匹配函数

Mag*_*s W 11 c++ sorting xcode compiler-errors

花了大约一个小时试图弄清楚为什么"Semantic issue - no matching function for call to 'swap'"当我尝试构建下面的类(在XCode中)时,我会得到20个类型的错误消息.

test.h

#include <iostream>
#include <string>
#include <vector>


class Test{
    std::vector<std::string> list;

    void run() const;
    static bool algo(const std::string &str1, const std::string &str2);
};
Run Code Online (Sandbox Code Playgroud)

TEST.CPP

#include "test.h"


void Test::run() const {
    std::sort( list.begin(), list.end(), algo );
}


bool Test::algo(const std::string &str1, const std::string &str2){
    // Compare and return bool
}
Run Code Online (Sandbox Code Playgroud)

大多数具有相同问题的人似乎已经使他们的算法成为类成员而不是静态成员,但这显然不是问题.

Mag*_*s W 23

事实证明这是一个非常简单的问题,但发现并不是很明显(并且错误消息在帮助中也没有做得很好):

删除const声明run()- voilá.

  • 错误消息应至少指向正确的方向,但您必须检查错误的全文,而不仅仅是XCode内联显示的内容. (2认同)

Vla*_*cow 8

编译器引用swap因为std::sort内部使用函数交换.但是由于成员函数run被声明为常量函数

void run() const;
Run Code Online (Sandbox Code Playgroud)

那么类本身的对象被认为是一个常量对象,因此数据成员列表也是一个常量对象

std::vector<std::string> list;
Run Code Online (Sandbox Code Playgroud)

因此编译器尝试swap使用常量引用的参数调用,甚至不是引用,也无法找到这样的函数.