检测偶数和奇数C ++向量迭代器

时间:2012-12-25 02:24:47

标签: c++ iterator

我搜索过,我很惊讶这还没有被问到。我知道如何用一个简单的循环来实现它,使用矢量迭代器怎么样?

for( std::vector<int>::iterator it = somevector.begin(); it != somevector.end(); ++it )
{
    //Conditions stating a certain vector has an even or odd index.
}

很抱歉没有澄清,我的意思是检测向量的索引是奇数还是偶数。

3 个答案:

答案 0 :(得分:5)

这将是一个简单的方法:

{
  bool is_even = true;
  for (const auto& v: somevector) {
    if (is_even) even_handler(v);
    else         odd_handler(v);
    is_even = !is_even;
  }
}

想要更复杂的解决方案吗?没问题:

#include <iostream>
#include <string>
#include <utility>
#include <vector>
using std::next;
template<typename Iter, typename Func, typename...Funcs>
void RotateHandlers(Iter b, Iter e, Func f, Funcs...fs) {
    if (b != e) {
        f(*b);
        RotateHandlers(next(b), e, fs..., f);
    }
}

int main() {
    std::vector<std::string> v({"Hello", "world", "it's", "really", "great", "to", "be", "here"});
    RotateHandlers(v.begin(), v.end(),
      [](const std::string& s){std::cout << "First|" << s << std::endl;},
      [](const std::string& s){std::cout << "Then |" << s << std::endl;},
      [](const std::string& s){std::cout << "And  |" << s << std::endl
                                         << "     |" << std::string(s.size(), '-') << std::endl;}
    );
    return 0;
}

请在此处查看:http://ideone.com/jmlV5F

答案 1 :(得分:3)

我猜你的意思是你想要检测当前的指数是偶数还是奇数:

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector<int> somevector;
    somevector.push_back(1);
    somevector.push_back(2);
    somevector.push_back(4);
    somevector.push_back(8);
    somevector.push_back(111605);

    for (auto it = somevector.begin(); it != somevector.end(); ++it)
    {
        // current index
        const auto index = std::distance(somevector.begin(), it);

        if ((index % 2) == 0) // even
        {
            std::cout << "Index " << index << " (even) is: " << *it;
        }
        else
        {
            std::cout << "Index " << index << " (odd) is: " << *it;
        }

        std::cout << std::endl;
    }
}

您可以使用std::distance获取迭代器之间的距离。 (索引距离开头的距离。)

答案 2 :(得分:0)

如果我在[上次编辑之前]正确理解了问题,则选项为:

bool is_odd(const std::vector<int> &somevector) {
    for( std::vector<int>::iterator it = somevector.begin(); it != somevector.end(); ++it ) {
        //Conditions stating a certain vector is even or odd.
        if (*it % 2 == 0) {
          return false; 
        }
    }
    return true;
}

分别为“偶数载体”。