使用STL中的stable_sort()函数进行排序

来源:互联网 发布:seo是干嘛的 编辑:程序博客网 时间:2024/06/03 15:56
#include<iostream>#include<vector>#include<algorithm>#include<iterator>using namespace std;typedef struct TagNode{    int value;    int index;}Node;      //TagNode结构体的别名Node bool myCmp(const Node& a,const Node& b) //声明两个引用a,b{    return a.value<b.value;}int main(int argc,char **argv)   //argc是命令行总的参数个数,argv是argc个参数{    vector<Node>coll;      //创建存储Node类型值的容器coll    Node tmp;    int num,idx = 0;    while(cin >> num && num)    {++idx;tmp.value = num;tmp.index = idx;coll.push_back(tmp);    }    stable_sort(coll.begin(),coll.end(),myCmp);    cout << "Index\tValue:" << endl;    vector<Node>::iterator pos;    for(pos = coll.begin();pos != coll.end();++pos)    {cout << pos->index << "\t" << pos->value << endl;    }    return 0;}

输入0结束输入数字
当遇到值相同的时候,索引号较小的排在前面:)

原创粉丝点击