0

私は検索しましたが、これがまだ尋ねられていないことに驚いています。単純なループでそれを行う方法は知っていますが、ベクトル反復子ではどうですか?

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

ベクトルのインデックスが奇数か偶数かを検出するという意味でした。

4

3 に答える 3

5

これは簡単な方法の 1 つです。

{
  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

于 2012-12-25T02:30:10.770 に答える
4

I'm going to guess you meant you wanted to detect if the current index is even or odd:

#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;
    }
}

You can get the distance between iterators with std::distance. (Index being distance from the start.)

于 2012-12-25T02:37:52.477 に答える
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;
}

それぞれ「偶数ベクトル」の場合。

于 2012-12-25T02:30:27.803 に答える