我有以下稀疏矩阵,其中包含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
.
您可以在这个常见问题解答中找到答案:如何迭代所有非零元素?
在你的情况下,它将是:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)