如何在 c++/犰狳中去除不连续的索引

How to shed non-contiguous indices in c++/armadillo

本文关键字:不连续 索引 c++      更新时间:2023-10-16

我正在寻找一种干净的方法来摆脱使用犰狳线性代数库进行C++的非连续索引。我在下面包含了一些代码,但似乎可能有更好的方法。任何建议表示赞赏。

以下代码用于从(列(向量a中删除ind中的索引,但感觉很笨拙。

for(uword k = ind.n_elem; k>0; k--){
        a.shed_row(ind(k-1));
}

有什么想法吗?

以下是使用模板化函数根据要排除的索引的(排序(uvec删除行的一种方法。您从std::set_difference获取缺少的索引,然后从那里开始。

#define ARMA_USE_CXX11
#include <armadillo>
#include <iostream>
template <class T>
T drop_rows(T a, arma::uvec exclude) {
    arma::uvec full_range = arma::regspace<arma::uvec>(0, a.n_rows - 1);
    std::vector<int> diff;
    std::set_difference(full_range.begin(), full_range.end(), 
                        exclude.begin(), exclude.end(), 
                        std::inserter(diff, diff.begin()));
    T b = a.rows(arma::conv_to<arma::uvec>::from(diff));
    return b;
}
int main() {
    arma::uvec exclude = {0, 1, 4};
    arma::vec a = arma::linspace<arma::vec>(100, 500, 5);
    arma::vec b = drop_rows(a, exclude);
    std::cout << b << std::endl;
    arma::mat A = arma::mat(5, 5, arma::fill::eye);
    arma::mat B = drop_rows(A, exclude);
    std::cout << B << std::endl;
    return 0;
}