gpt4 book ai didi

c++ - 遍历 uBlas 稀疏矩阵的非零元素

转载 作者:可可西里 更新时间:2023-11-01 18:18:12 27 4
gpt4 key购买 nike

我有以下包含 O(N) 元素的稀疏矩阵

boost::numeric::ublas::compressed_matrix<int> adjacency (N, N);

我可以像下面这样在 O(N^2) 时间内编写一个强力双循环遍历所有条目,但这会太慢。

for(int i=0; i<N; ++i)
for(int j=0; j<N; ++j)
std::cout << adjacency(i,j) std::endl;

如何在 O(N) 时间内只循环非零条目?对于每个非零元素,我想访问它的值和索引 i,j

最佳答案

您可以在此常见问题解答中找到答案:How to iterate over all non zero elements?

在您的情况下,它将是:

typedef boost::numeric::ublas::compressed_matrix<int>::iterator1 it1_t;
typedef boost::numeric::ublas::compressed_matrix<int>::iterator2 it2_t;

for (it1_t it1 = adjacency.begin1(); it1 != adjacency.end1(); it1++)
{
for (it2_t it2 = it1.begin(); it2 != it1.end(); it2++)
{
std::cout << "(" << it2.index1() << "," << it2.index2() << ") = ";
std::cout << *it2 << std::endl;
}
}

关于c++ - 遍历 uBlas 稀疏矩阵的非零元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1795658/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com