我这里有一个矩阵,我想要的是将它的元素复制到一个二维数组或向量中(我更喜欢),并以一种保持索引的方式对它们进行排序。
例如,对于这个矩阵,我想保留这些数据:(这些数据包含索引,并且它们是经过排序的)
1-5
1-2
2-4
4-5
2-5
1-4
3-5
1-3
3-4
2-3
现在你有什么建议,我该怎么做呢?
发布于 2014-04-09 03:26:03
#include <vector> // for std::vector
#include <algorithm> // for std::sort
// your matrix
int matrix[5][5] = { ... };
// we use a struct to store entries with coordiantes
struct Entry {
int row, col;
int value;
};
// copy matrix data to vector
std::vector<Entry> entries;
for(int i=0; i<5; i++) {
for(int j=i+1; j<5; j++) {
entries.push_back({i,j,matrix[i][j]});
}
}
// sort vector
std::sort(entries.begin(), entries.end(),
[](const Entry& a, const Entry& b) {
return a.value> b.value;
});
发布于 2014-04-09 03:00:59
我会说使用链表。为每个元素创建一个节点,使每个节点具有以下内容
node{
int data;
int row;
int col;
node *next;
}
将这些节点放入一个数组中,这样就有了节点数组。
完成后,您可以使用每个节点的数据成员对数组进行排序。
由于节点的行和列部分不变,因此您可以使用它来保留矩阵中每个元素的位置。
https://stackoverflow.com/questions/22945769
复制相似问题