关于在c++中迭代数组的问题
Question about iterating through array in c++
我有一个不一定是满的数组。
它可以非常稀疏。
有没有一种好的方法来迭代这个数组而不访问所有可能的索引?(c++数组迭代器?)
或者,即使我使用数组迭代器,它与访问每个索引并检查值没有什么不同吗?
是的,如果您使用迭代器,它与访问每个索引并检查值是一样的,并且没有好方法可以跳过逻辑漏洞。你可以保留一个好的索引列表,但如果你这么做了,为什么不直接用列表来存储数据呢?
如果您的数据非常稀疏,可能更好的数据结构是std::map
,甚至是std::unordered_map
,这取决于您的应用程序。它们具有不错的查找时间,同时不会浪费太多空间,就像数组那样。
关联数组是您要构建的。我建议你找一个能为你做这些的图书馆!
如果需要模拟数组的键/值关联,只需使用包含std::pair的std::map。然后,您可以使用索引(键)检索您的值,并仅在您的实际值集上快速迭代。
http://en.cppreference.com/w/cpp/container/mapstd::map具有像操作符[]一样的语法方便,可以充当数组。
如果你真的需要坚持你的基于数组的解决方案boost::filter_iterator
可能是有用的。下面是一个整数数组的小示例:
#include <algorithm>
#include <iostream>
#include <boost/iterator/filter_iterator.hpp>
struct is_not_null {
bool operator()(int* t) {
return t != NULL ? true : false;
}
};
int main()
{
int* a[] = {NULL, NULL, NULL, NULL, NULL, NULL };
a[0] = new int[3];
a[0][0] = 1; a[0][1] = 2; a[0][2] = 3;
a[3] = new int[3];
a[3][0] = 3; a[3][1] = 4; a[3][2] = 5;
a[5] = new int[3];
a[5][0] = 5; a[5][1] = 6; a[5][2] = 7;
typedef int** base_iterator;
typedef boost::filter_iterator<is_not_null, base_iterator>
FilterIter;
for(FilterIter it = boost::make_filter_iterator< is_not_null >(a, a + 6);
it != boost::make_filter_iterator< is_not_null >(a + 6, a + 6);
++it) {
std::cout << (*it)[0] << " " << (*it)[1] << " " << (*it)[2] << std::endl;
}
// nevermind the leaks
return 0;
}
相关文章:
- 数组C++问题中最大和第二大的数字
- 二维数组问题
- 数组问题:变量周围的堆栈'arr'已损坏
- 无符号字符数组问题
- 数组问题(if (zeds[i].x == zeds[i].x))
- 字符数组问题
- C++中的turbo数组问题
- 输入和输出的2D字符数组问题
- 多维数组问题
- 指针和数组指向数组问题
- 如何随机排列数组问题
- C++ 多维数组问题 - 多次打印条目
- C++ 2D 读入数组问题
- C++读入 2D 数组问题
- 指针和多维数组问题
- C++多项式类,指针数组问题
- 在数组问题(C++)中查找偶数
- 二维std::数组问题
- 向量/数组问题,不能给变量赋索引/不能使用变量作为数组大小(索引)c++
- 指针数组问题