[英]Boost transformed conversion to vector error
我是使用 boost 適配器的新手,我正在使用以下代碼將向量一 class 轉換為轉換后的版本。
boost::transformed 的返回類型與預期不符。 有人可以說明我在這里缺少什么:
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];
}
行std::vector<std::pair<blabla2, double>> histogramtest = histogram;
給出錯誤
而std::pair<blabla2, double> x = histogram[0];
工作正常。 為什么呢?
返回值為boost::transformed_range<decltype(foo), std::vector<blabla>>
,而不是std::vector<std::pair<blabla2, double>>
。 如果你想達到預期的類型,你應該這樣做:
std::vector<std::pair<blabla2, double>> histogramtest;
boost::copy( test | transformed(foo), std::back_inserter(histogramtest));
您需要將范圍復制到向量中。
例如
#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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.