decltype of boost::make_zip_iterator?

decltype of boost::make_zip_iterator?

本文关键字:zip iterator make of boost decltype      更新时间:2023-10-16

我有以下代码:

std::vector<PriceQuote, tbb::scalable_allocator<PriceQuote> > cBids(maxSize);
std::vector<PriceQuote, tbb::scalable_allocator<PriceQuote> > cAsks(maxSize);
auto zipBidsAsks = boost::make_zip_iterator(boost::make_tuple(cBids.begin(), cAsks.begin()));

如果我想decltype返回值,这样我就可以将其存储在boost::make_zip_iterator返回的任何decltype中,而不是将其存储到auto中。那个代码是什么样子的?

我试过:

typedef decltype(boost::make_zip_iterator(std::vector<PriceQuote>, std::vector<PriceQuote>)) zipper_type;
// type referred to by zipper_type::iterator
typedef std::iterator_traits<zipper_type::iterator>::value_type zipped_type;
 zipped_type zipBidsAsks = boost::make_zip_iterator(boost::make_tuple(cBids.begin(), cAsks.begin()));

但这根本不起作用。最后,如果我想在zipBidsAsks上迭代并得到每个<0><1>。这是怎么做到的?

访问代码现在给出一个错误:

    struct PriceBookEventData
{
    timeval ts;
    unsigned totalSize;
    unsigned maxSize;

    typedef decltype
    (
         boost::make_zip_iterator(boost::tuple<std::vector<PriceQuote>::iterator,
                                               std::vector<PriceQuote>::iterator>())
    ) zipper_type;
     zipper_type zipBidsAsks;
};
void AGUI::HandlePriceBookChange(const PriceBookEventData pbed)
{
int k = 0;
while(0 != stop--)
{
    PriceQuote pqb = boost::get<0>(pbed.zipBidsAsks[k]);
    PriceQuote pqa = boost::get<1>(pbed.zipBidsAsks[k]);

/data/cbworkspace/AGUI/AGUI.cpp|101|error: no matching function for call to ‘get(boost::detail::operator_brackets_result<boost::zip_iterator<boost::tuples::tuple<__gnu_cxx::__normal_iterator<PriceQuote*, std::vector<PriceQuote> >, __gnu_cxx::__normal_iterator<PriceQuote*, std::vector<PriceQuote> > > >, boost::tuples::cons<PriceQuote&, boost::tuples::cons<PriceQuote&, boost::tuples::null_type> >, boost::tuples::cons<PriceQuote&, boost::tuples::cons<PriceQuote&, boost::tuples::null_type> > >::type)’|

我不知道为什么要使用decltype而不是auto来计算类型,后者是专门为此类情况设计的。相反,使用decltype是很麻烦的。

除了给boost::make_zip_iterator一对向量,而不是给tuple一个向量interator之外,你已经接近了你的尝试。

试试这个

typedef decltype(
  boost::make_zip_iterator(
    boost::tuple<
      std::vector<PriceQuote>::iterator, 
      std::vector<PriceQuote>::iterator>()
  ) 
) zipper_type;

至于在zip迭代器上迭代,这里有一个简单的例子:

#include <iostream>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/tuple/tuple.hpp>
#include <vector>
int main()
{
    std::vector<int> v1{1,2,3,4}, v2{10,20,30,40};
    std::for_each(
        boost::make_zip_iterator(boost::make_tuple(v1.begin(), v2.begin())),
        boost::make_zip_iterator(boost::make_tuple(v1.end(), v2.end())),
        []( boost::tuple<int, int> const& tup ) {
            std::cout 
              << boost::get<0>(tup) 
              << ", " 
              << boost::get<1>(tup) 
              << std::endl;
        }
    );
}

输出:

1, 10
2, 20
3, 30
4, 40