关于在c++中迭代数组的问题

Question about iterating through array in c++

本文关键字:数组 问题 迭代 c++      更新时间:2023-10-16

我有一个不一定是满的数组。

它可以非常稀疏。

有没有一种好的方法来迭代这个数组而不访问所有可能的索引?(c++数组迭代器?)

或者,即使我使用数组迭代器,它与访问每个索引并检查值没有什么不同吗?

是的,如果您使用迭代器,它与访问每个索引并检查值是一样的,并且没有好方法可以跳过逻辑漏洞。你可以保留一个好的索引列表,但如果你这么做了,为什么不直接用列表来存储数据呢?

如果您的数据非常稀疏,可能更好的数据结构是std::map,甚至是std::unordered_map,这取决于您的应用程序。它们具有不错的查找时间,同时不会浪费太多空间,就像数组那样。

关联数组是您要构建的。我建议你找一个能为你做这些的图书馆!

如果需要模拟数组的键/值关联,只需使用包含std::pair的std::map。然后,您可以使用索引(键)检索您的值,并仅在您的实际值集上快速迭代。

http://en.cppreference.com/w/cpp/container/map

std::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;
}