xcode sort() - 没有用于调用“交换”的匹配函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28761802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:44:20  来源:igfitidea点击:

sort() - No matching function for call to 'swap'

c++xcodesortingcompiler-errors

提问by Magnus W

Just spent about an hour trying to figure out why I would get 20 error messages of the type "Semantic issue - no matching function for call to 'swap'"when I try to build the following class (in XCode).

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

test.h

测试.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);
};

test.cpp

测试.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
}

Most of the people with the same problem seem to have made their algorithm a class member instead of a static member, but that is clearly not the problem here.

大多数遇到同样问题的人似乎将他们的算法设为类成员而不是静态成员,但这显然不是这里的问题。

回答by Magnus W

It turns out it's a very simple problem, but not very obvious to spot (and the error message doesn't do a very good job in helping out either):

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

Remove the constdeclaration on run()- voilá.

删除const关于run()- voilá的声明。

回答by Vlad from Moscow

The compiler refers to swapbecause std::sortinternally uses function swap. However as member function runis declared as constant function

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

void run() const;

then the object of the class itself is considered as a constant object and hence data member list also is a constant object

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

std::vector<std::string> list;

So the compiler tries to call swapwith parameters that are constant references or even are not references and can not find such a function.

因此,编译器尝试swap使用常量引用甚至不是引用的参数进行调用,并且找不到这样的函数。