How can I use C++11 variadic templates to define a vector-of-tuples backed by a tuple-of-vectors?

后端 未结 6 670
夕颜
夕颜 2020-12-13 11:20

Suppose I have a bunch of vectors:

vector v1;
vector v2;
vector v3;

all of the same length. Now, for ev

6条回答
  •  失恋的感觉
    2020-12-13 11:56

    An alternative to all the variadic template juggling is to use the boost::zip_iterator for this purpose. For example (untested):

    std::vector ia;
    std::vector d;
    std::vector ib;
    
    std::for_each(
      boost::make_zip_iterator(
        boost::make_tuple(ia.begin(), d.begin(), ib.begin())
        ),
      boost::make_zip_iterator(
        boost::make_tuple(ia.end(), d.end(), ib.end())
        ),
      handle_each()
      );
    

    Where your handler, looks like:

    struct handle_each :
      public std::unary_function&, void>
    {
      void operator()(const boost::tuple& t) const
      {
        // Now you have a tuple of the three values across the vector...
      }
    };
    

    As you can see, it's pretty trivial to expand this to support an arbitrary set of vectors..

提交回复
热议问题