索引的排序向量

gui*_*nny 1 c++ sorting vector

我有一个非常简单的问题,我认为我只是在做一些愚蠢的事情,但几个小时都找不到这个bug.

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

typedef unsigned int uint;

enum {ASCEND, DESCEND};

template<typename T>
bool ascend_sort(pair<uint, T> i, pair<uint, T> j){return j.second>i.second;}

template<typename T>
bool descend_sort(pair<uint, T> i, pair<uint, T> j){return i.second>j.second;}

template<typename T>
void sortIdx(vector<uint>& idx, const vector<T>& src, int dir=ASCEND){
    vector< pair<uint, T>  > tmp (src.size());
    for (uint i=0; i<src.size(); i++){
        tmp.push_back(pair<uint, T>(i, src[i]));
        cout << i << " " << src[i] << " \n";
    }

    if (dir==ASCEND){
        sort(tmp.begin(), tmp.end(), ascend_sort<T>);
    }else{
        sort(tmp.begin(), tmp.end(), descend_sort<T>);
    }

    idx.resize(src.size());

    for (uint i=0; i<src.size(); i++){
        idx[i] = (tmp[i].first);
        cout << tmp[i].first << " \n" ;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么http://ideone.com/HOnvI工作且   http://ideone.com/R6H0n不....

代码只有在上升和下降排序方面有所不同.我还测试了没有map的排序(直接对矢量排序),它在那里工作正常.

Att*_*ila 5

这条线

vector< pair<uint, T>  > tmp (src.size());
Run Code Online (Sandbox Code Playgroud)

创建一个src.size()用默认元素填充的大小向量(这里:pair(0,0.0));

.push_back()该数组的末尾(现在的大小增加了额外的元件(2*src.size())

然后在排序后,您只打印第一个src.size()元素,这些元素都是最初的0,0.0个元素

要修复,只需将向量声明为空:

vector< pair<uint, T>  > tmp;
Run Code Online (Sandbox Code Playgroud)