Reputation: 1532
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....
the codes only differ in sorting ascendantly and descendantly. I also tested sorting without map (sort the vector directly), and it works fine there.
Upvotes: 1
Views: 602
Reputation: 28762
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));
The .push_back()
adds additional elements to the end of that array (now the size of (2*src.size()
)
Then after the sort you print only the first src.size()
elements, which are all the initial 0,0.0 ones
To fix, just declare the vector empty:
vector< pair<uint, T> > tmp;
Upvotes: 5