2

有没有一种简单的方法可以将迭代器与 int 进行比较?

我有一个这样的循环:

for (std::vector<mystruct>::const_iterator it = vec->begin(); it != vec->end(); ++it)

我不想循环遍历整个向量,而只想循环遍历前 3 个元素。但是,以下内容无法编译:

for (std::vector<mystruct>::const_iterator it = vec->begin(); it < 3; ++it)

有没有达到同样效果的好方法?

4

4 回答 4

4

std::next(vec->begin(), 3);将是第一个之后 3 个位置的迭代器,因此您可以对其进行比较:

for (std::vector<mystruct>::const_iterator it = vec->begin(); it != std::next(vec->begin(), 3); ++it)

不过,您的向量中至少需要包含 3 个元素。

于 2013-05-14T02:17:44.810 回答
4

既然它是一个向量,为什么不直接访问它的位置呢?

if (vec->size() > 0)
{
    for (int i =0; i<3 && i< vec->size(); i++)
    {
        // vec[i] can be accessed directly
        //do stuff 
    } 
}
于 2013-05-14T02:56:28.693 回答
3

我要小心,因为您很容易遇到栅栏错误。

这适用于随机访问容器(如vectorand ),但由于我很懒,所以array不做 ADL :begin

template<typename Container>
auto nth_element( Container&& c, std::size_t n )->decltype( std::begin(c) )
{
  auto retval = std::begin(c);
  std::size_t size = std::end(c) - retval;
  retval += std::min( size, n );
  return retval;
}

std::end(c)如果n太大,它会返回。

所以你得到:

for( auto it = vec->cbegin(); it != nth_element(vec, 3); ++it) {
   // code
}

它优雅地处理大小小于 3 的向量。

其基本核心是在随机访问迭代器上,迭代器的区别是ptrdiff_t——一个整数类型——你可以在迭代器中添加整数类型来移动。我只是加入了一个辅助函数,因为如果你能提供帮助,你应该只在孤立的函数中进行非平凡的指针算术(并且迭代器上的算术是指针算术)。

支持非随机访问迭代器是做一些特征检查的问题。除非你真的需要,否则我不会担心。

请注意,这个答案取决于一些 C++11 特性,但没有晦涩难懂的特性。你需要#include <iterator>forstd::begin并且std::end也许<algorithm>for std::min

于 2013-05-14T02:39:30.777 回答
0

当然,您可以简单地从头开始三个元素。

for (std::vector<mystruct>::const_iterator it = vec->cbegin(); it != vec->cbegin() + 3; ++it)

但是,这可能容易出错,因为在向量少于 3 个元素的情况下,您可能会尝试访问末尾以外的内容。我认为当这种情况发生时你会得到一个例外,但你可以通过以下方式防止它:

for(std::vector<mystruct>::const_iterator it = vec->cbegin(); it != vec->cend() && it != vec->cbegin() + 3; ++it)

请注意 cbegin() 和 cend() 的使用,因为您要求使用 const_iterator,尽管这些仅在 c++11 中可用。您可以轻松地将 begin() 和 end() 与 const_iterator 一起使用。

于 2014-05-20T11:37:59.367 回答