【发布时间】:2013-04-27 23:52:02
【问题描述】:
我想按 x 对 n 维点的列表进行排序并存储它们的原始索引:
original=[(3,2,3)(1,2,1)(5,1,5)]
排序后:
[(1,2,1)(3,2,3)(5,1,5)]
和索引:
store=[1,0,2]
我用vector< vector<double>来存储n维点:
a[0][0] = x, a[0][1] = y, a[0][2] = z, ...
我写了一个mergesort来做,通过引用传递source调用
并通过引用传输result 调用以获取索引。
我遇到了一个问题,如果我想打印结果,程序会关闭。
#include <vector>
#include <cmath>
#include <cfloat>
#include <iostream>
#include <algorithm>
using namespace std;
void merge(vector< vector<double> >& source, vector< int >& result, int lmin, int lmax, int rmin, int rmax){
int i = lmin, j = rmin;
while(i <= lmin && j <= rmin){
//left > right
if(source[i][0] > source[j][0]){
source[i].swap(source[j]);
//exchange result
int temp = result[j];
result[j] = result[i];
result[i] = temp;
i ++;
}
else if(source[i][0] < source[j][0])
source[i].swap(source[j]);
j ++;
}
}
void merge_sort(vector< vector<double> >& source, vector< int >& result, int min, int max){
if(max - min == 0){
result[min] = min;
return;
}
int median = (max - min) / 2;
merge_sort(source, result, min , median);
merge_sort(source, result, median + 1 , max);
merge(source, result, min, median, median + 1, max);
}
int main(){
vector < vector<double> >test (8, vector<double>(3));
vector < int >result (8);
vector < vector<double> >ttt;
test[0][0]= 10;
test[0][1]= 20;
test[0][2]= 30;
//(1,2,3)
test[1][0]= 1;
test[1][1]= 2;
test[1][2]= 3;
//(1000,2000,3000)
test[2][0]= 1000;
test[2][1]= 2000;
test[2][2]= 3000;
//(100,200,300)
test[3][0]= 100;
test[3][1]= 200;
test[3][2]= 300;
//(100,200,300)
test[4][0]= 100;
test[4][1]= 200;
test[4][2]= 302;
//(100,200,300)
test[5][0]= 100;
test[5][1]= 200;
test[5][2]= 3030;
//(100,200,300)
test[6][0]= 1000000;
test[6][1]= 2000000;
test[6][2]= 3000000;
test[7][0]= 10;
test[7][1]= 20;
test[7][2]= 30.5;
merge_sort(test, result, 0 , 7);
for (int i = 0; i < test.size(); i ++){
for(int j = 0; j < test[i].size(); j ++){
cout << test[i][j] << endl;
}
}
for(int i = 0; i < result.size(); i ++)cout << result[i] << endl;
}
【问题讨论】:
-
你试过在调试器中运行它吗?它在哪里崩溃?另外,尝试进行一个较小的崩溃测试,然后对其进行调查。
-
不好意思,没用过,以后会学习的。
-
您需要编写自己的归并排序吗?我在想你可以有索引的 std::vector
并使用 std::sort 和适当的函数对象对该向量进行排序。 -
@liang-yupan 查看this 获取 gdb 教程(以防你在 unix/linux 机器上。dnt knw abt windows)
-
std::sort here: cplusplus.com/reference/algorithm/sort