简体   繁体   中英

Boost transformed conversion to vector error

I am new to using boost adapters, I am using the following code for conversion of a vector one class to transformed version.

The return type of boost::transformed is not as per expectation. Can someone please illuminate as to what I am missing here:

class blabla
{
    public:
    int x;
};

class blabla2
{
    public:
    int  y;
    blabla2(int a)
    {
        y=a;
    }
};


int main()
{
    using namespace boost::adaptors;
    std::vector<blabla> test;

    auto foo = [](const blabla& A) -> std::pair<blabla2, double> {
        return std::make_pair(blabla2(A.x), double(A.x));
    };

    const auto histogram = test | boost::adaptors::transformed(foo);
    // std::vector<std::pair<blabla2, double>> should be return type? 

    std::vector<std::pair<blabla2, double>> histogramtest = histogram; ----> this line gives error unexpectedly. Why is it so?
    std::pair<blabla2, double> x = histogram[0];
}

The line std::vector<std::pair<blabla2, double>> histogramtest = histogram; gives error

While std::pair<blabla2, double> x = histogram[0]; works correctly. Why is that so?

The return value is boost::transformed_range<decltype(foo), std::vector<blabla>> , not std::vector<std::pair<blabla2, double>> . If you want to achieve expected type, you should do something like that:

std::vector<std::pair<blabla2, double>> histogramtest;
boost::copy( test | transformed(foo), std::back_inserter(histogramtest));

You need to copy the range into a vector.

eg

#include "boost/range/adaptor/transformed.hpp"
#include "boost/range/algorithm.hpp"
#include <iostream>
#include <vector>

class blabla
{
public:
    int x;
};

class blabla2
{
public:
    int  y;
    blabla2(int a)
    {
        y = a;
    }
};


int main()
{
    std::vector<blabla> test = { {1}, {2}, {3} };

    auto foo = [](const blabla& A) -> std::pair<blabla2, double> {
        return std::make_pair(blabla2(A.x), double(A.x));
    };

    const auto test_range = test | boost::adaptors::transformed(foo);

    std::vector<std::pair<blabla2, double>> test_output_vector;
    boost::range::copy(test_range, std::back_inserter(test_output_vector));

    for (const auto& [b, v] : test_output_vector) {
        std::cout << b.y << ", " << v << "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM