【问题标题】:Sorting a stl::List of abstract data types对 stl::抽象数据类型列表进行排序
【发布时间】:2014-08-09 10:27:28
【问题描述】:

我可以知道如何将stl::list::sort 函数与抽象数据类型的外部函数一起使用吗?

构造函数的示例代码如下所示:

ADType::ADType(string name, int object){
//constructor code
}

对于方法:

using <list>
using namespace std;

bool compare_Object(ADType& first, ADType& second){
//search algorithm
return true;
}

int main(){
ADType test1 = ADType("Test 1", 123);
ADType test2 = ADType("Test 3", 142);
ADType test3 = ADType("Test 2", 200);
list<ADType> testlist;
testlist.push_back(test1);
testlist.push_back(test2);
testlist.push_back(test3);
testlist.sort(compare_Object);
//code to print out objects in list
}

上面的行给了我函数调用缺少参数列表的错误 C3867 和不接受参数的函数的 C2660。我刚刚发布的代码有问题吗?

【问题讨论】:

  • 您至少需要为ADType IMHO 提供一个复制或移动构造函数。
  • 哪一行出现错误?
  • 你会遇到比使用sort更大的问题,见stackoverflow.com/a/9241731/362589

标签: c++ list sorting stl


【解决方案1】:

您的示例代码存在一些问题(不完整、可能的切片、不正确的 const)并且没有显示任何多态性。

在 C++11 中你可以这样做:

#include <iostream>
#include <memory>
#include <list>

struct A {
    virtual ~A() {}
    virtual void print() const { std::cout << "A\n"; }
};

struct B : A {
    virtual void print() const { std::cout << "B\n"; }
};


inline bool operator < (const A& a, const A& b) {
    return dynamic_cast<const A*>(&a) && dynamic_cast<const B*>(&b);
}

template <typename T>
inline bool less_unique_ptr(const std::unique_ptr<A>& a, const std::unique_ptr<A>& b) {
    return *a < *b;
}

int main (int argc, char *argv[])
{
    std::list<std::unique_ptr<A>> ptr_list;
    ptr_list.emplace_back(new B);
    ptr_list.emplace_back(new B);
    ptr_list.emplace_back(new A);
    ptr_list.sort(less_unique_ptr<A>);

    for(const auto& e : ptr_list)
        e->print();

    return 0;
}

【讨论】:

  • 多态性和切片与OP的问题有什么关系?他发布了一些由于特定原因无法编译的代码;您的回答说明了一些重要但无关紧要的事情。
  • 虽然它并没有真正回答问题,但我想我知道他的意思并相应地修改了实际文件。应该放置更多关于课程的信息以获得更好的答案。
【解决方案2】:

更简单的解决方法是将比较方法实现为静态方法,因此不需要对象实例即可使用该方法。

static bool compare_Object(BaseObj& first, BaseObj& second){
    return first.getLength() > second.getLength();
    // return true give me error since it can't really sort.
}

BaseObj 类:

    BaseObj::BaseObj(int a) {
          length = a;
    }

    int BaseObj::getLength() {
          return length;
    }

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 2014-06-29
    • 2015-06-24
    • 2020-02-23
    • 1970-01-01
    • 2011-01-26
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多