這並不美觀,並且依靠使用其模板參數挑選矩陣 - 但它有效。
#include <Eigen/Core>
#include <algorithm>
#include <vector>
// Simple little templated comparison functor
template <typename MatrixT>
bool compareRows(MatrixT a, MatrixT b) {
return a(0,0) < b(0,0);
}
// These are the 6 template arguments to every Eigen matrix
template <typename Scalar, int rows, int cols, int options, int maxRows, int maxCols>
Eigen::Matrix<Scalar, rows, cols, options, maxRows, maxCols> sortMatrix(
Eigen::Matrix<Scalar, rows, cols, options, maxRows, maxCols> target
) {
// Manually construct a vector of correctly-typed matrix rows
std::vector<Eigen::Matrix<Scalar, 1, cols>> matrixRows;
for (unsigned int i = 0; i < target.rows(); i++)
matrixRows.push_back(target.row(i));
std::sort(
matrixRows.begin(),
matrixRows.end(),
compareRows<Eigen::Matrix<Scalar, 1, cols>>
);
Eigen::Matrix<Scalar, rows, cols, options, maxRows, maxCols> sorted;
for (unsigned int i = 0; i < matrixRows.size(); i++)
sorted.row(i) = matrixRows[i];
return sorted;
}
值得慶幸的是,由於模板參數推導,你可以簡單地調用這個搞成這個樣子:
Eigen::Matrix3f myMatrix;
// Fill in contents here
Eigen::Matrix3f sorted = sortMatrix(myMatrix);
,我幾乎可以肯定有一個更優雅的方式來做到這一點,但我不能現在想想它。而且,因爲它使用std::vector
,所以需要使用-std=c++11
或更好的編譯方式。
感謝,我去了這一點,然後儘快給您 – user1420
你不不需要做這個過於複雜的模板材料;一個簡單的'Eigen :: MatrixXd'就可以做到。 – xjcl