首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >自定义排序C++列表

自定义排序C++列表
EN

Stack Overflow用户
提问于 2018-12-07 16:03:53
回答 1查看 113关注 0票数 0
代码语言:javascript
运行
复制
//
//  TemplateArray.cpp
//  C++
//
//  Created by FatJoe  on 03/12/2018.
//  Copyright © 2018 FatJoe . All rights reserved.
//

#include <stdio.h>
#include <iostream>

/*

 This code demonstrates representing an array and array adder using objects
 Overloading the [] operator

 */

#include<list>
#include <map>

using namespace std;

class person{

public:
    int i;
    person(int j):i(j){}


};

class comparer{

public:
    bool operator()(const person& first, const person& second)const{
        cout << "operator() called" << endl;
        return true;
    };
};

int main(){

    list<person> personlist;
    list<person>::iterator itr = personlist.begin();
    personlist.insert(itr,person(1));
    personlist.insert(itr,person(2));
    personlist.insert(itr,person(3));


    for(itr=personlist.begin(); itr!=personlist.end(); itr++){
        cout << (*itr).i << "Person no." << endl;
    };

    personlist.sort(comparer());


    for(itr=personlist.begin(); itr!=personlist.end(); itr++){
        cout << (*itr).i << "Person no." << endl;
    };

    personlist.sort(comparer());


    for(itr=personlist.begin(); itr!=personlist.end(); itr++){
        cout << (*itr).i << "Person no." << endl;
    };


    return 0;
}

我正在尝试编写我自己的排序标准,我正在测试我自己的一些代码。

在我的比较器函数器中,我返回true,这意味着第一个参数将与第二个参数交换。

然而,我很难理解为什么如果列表中有3个元素,为什么比较函数被调用了3次,它肯定是compare(1,2)然后compare(2,3)?

EN

Stack Overflow用户

发布于 2018-12-07 16:08:04

除了n log n复杂度之外,std::list的排序算法是未指定的。您需要查看您正在使用的任何运行时库的源代码,以了解它是如何实现的。您应该能够使用调试器单步执行代码。

由于您的比较函数不符合Compare规范,因此您的代码具有未定义的行为。

票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53665476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档