简体   繁体   English

索引的排序向量

[英]sort vector for index

I have a very simple question, and I think I am simply doing something stupid, but cannot find the bug for hours.... 我有一个非常简单的问题,我想我只是在做一些愚蠢的事情,但几个小时都找不到该错误。

#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" ;
    }
}

Why does http://ideone.com/HOnvI work and http://ideone.com/R6H0n not.... 为什么http://ideone.com/HOnvI可以工作,而http://ideone.com/R6H0n不能。...

the codes only differ in sorting ascendantly and descendantly. 这些代码仅在升序和降序排序上有所不同。 I also tested sorting without map (sort the vector directly), and it works fine there. 我还测试了没有地图的排序(直接对向量进行排序),并且在那里工作正常。

The line 线

vector< pair<uint, T>  > tmp (src.size());

Creates a vector of size src.size() filled with default elements (here: pair(0, 0.0)); 创建一个大小为src.size()的向量, src.size()填充默认元素(此处为:pair( src.size() ));

The .push_back() adds additional elements to the end of that array (now the size of (2* src.size() ) .push_back()在该数组的末尾添加了其他元素(现在的大小为(2 * src.size()

Then after the sort you print only the first src.size() elements, which are all the initial 0,0.0 ones 然后,在排序之后,只打印第一个src.size()元素,它们都是初始的0,0.0个元素

To fix, just declare the vector empty: 要修复,只需将向量声明为空:

vector< pair<uint, T>  > tmp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM