【问题标题】:sort() - No matching function for call to 'swap'sort() - 调用“交换”没有匹配的函数
【发布时间】:2015-04-29 23:19:58
【问题描述】:

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

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

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
}

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

【问题讨论】:

    标签: c++ xcode sorting compiler-errors swap


    【解决方案1】:

    事实证明这是一个非常简单的问题,但不是很明显(而且错误消息也不能很好地帮助解决问题):

    删除run() 上的const 声明 - 瞧。

    【讨论】:

    • 错误信息至少应该指向正确的方向,但您必须检查错误的全文,而不仅仅是 XCode 内联显示的内容。
    【解决方案2】:

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

    void run() const;
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多