我有一个int
的矩阵。
对存储在std::vector
中。 我想对这个向量
进行排序,这样排序之后,当遍历它时,它会按顺序给出矩阵的元素。 下面是一个示例代码:
#include <vector>
#include <algorithm>
int main()
{
int matrix[2][2];
matrix[0][0] = 4;
matrix[0][1] = 3;
matrix[1][0] = 7;
matrix[1][1] = 6;
std::vector<std::pair<int, int>> pair_indices;
pair_indices.push_back(std::make_pair(0, 0));//Row 0, column 0, corresponds to entry 4
pair_indices.push_back(std::make_pair(0, 1));//Row 0, column 1, corresponds to entry 3
pair_indices.push_back(std::make_pair(1, 0));//Row 1, column 0, corresponds to entry 7
pair_indices.push_back(std::make_pair(1, 1));//Row 1, column 1, corresponds to entry 6
std::sort(pair_indices.begin(), pair_indices.end(), [&](int index_left, int index_right) {
int i1, j1, i2, j2;
i1 = pair_indices[index_left].first;
j1 = pair_indices[index_left].second;
i2 = pair_indices[index_right].first;
j2 = pair_indices[index_right].second;
return matrix[i1][j1] > matrix[i2][j2];//Descending order
}
);
//At this point, I would like pair_indices to be: [ <1,0> | <1,1> | <0,0> | <0,1> ]
getchar();
return(0);
}
上述代码在\include\xutility
和\include\algorith
中没有编译错误。 上面源代码中的错误是:
see reference to function template instantiation 'void std::sort<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,main::<lambda_95ed4bac887c9dd3f80c928a0bd63c0f>>(const _RanIt,const _RanIt,_Pr)' being compiled
with
[
_Ty=std::pair<int,int>,
_RanIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<std::pair<int,int>>>>,
_Pr=main::<lambda_95ed4bac887c9dd3f80c928a0bd63c0f>
]
感谢任何帮助。
比较器应该采用两个元素。 您传递的comaraptor接受int
s,但向量的元素是std::pair
。
#include <vector>
#include <algorithm>
#include <utility>
#include <iostream>
int main()
{
int matrix[2][2];
matrix[0][0] = 4;
matrix[0][1] = 3;
matrix[1][0] = 7;
matrix[1][1] = 6;
using index2d = std::pair<int,int>;
std::vector<std::pair<int, int>> pair_indices;
pair_indices.push_back(std::make_pair(0, 0));//Row 0, column 0, corresponds to entry 4
pair_indices.push_back(std::make_pair(0, 1));//Row 0, column 1, corresponds to entry 3
pair_indices.push_back(std::make_pair(1, 0));//Row 1, column 0, corresponds to entry 7
pair_indices.push_back(std::make_pair(1, 1));//Row 1, column 1, corresponds to entry 6
std::sort(pair_indices.begin(),
pair_indices.end(),
[&matrix](const index2d& a,const index2d& b) {
return matrix[a.first][a.second] > matrix[b.first][b.second];//Descending order
}
);
for (const auto& p : pair_indices) {
std::cout << matrix[p.first][p.second] << '\n';
}
// getchar();
return(0);
}
输出:
7
6
4
3
对于std::pair
,您不需要#include
。 代码可以在没有它的情况下编译,但是你最好包含你所使用的内容。 另外,我将使用size_t
作为索引,而不是int
。