gpt4 book ai didi

c++ - boost 元组+变换

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:39 25 4
gpt4 key购买 nike

是否可以做到以下几点。

假设我的 boost 元组有 <std::string, T>

我想使用 std::transform + mem_fun 仅将 std::string 元素插入相应的 vector 中。是否有可能或者我们需要使用循环和 push_back(get<0>)...

即以下不喜欢编译...(未知类型...)

result.resize(storage.size())
std::transform(storage.begin(), storage.end(), result.begin(), std::mem_fun(&boost::get<0>));

这是一个例子(尝试其中一个评论):

#include <boost/tuple/tuple.hpp>
#include <vector>
#include <string>
#include <algorithm>
#include <boost/bind.hpp>

template <typename T>
class TestClass
{
private:
typedef boost::tuple<std::string,T> PairType;
std::vector<PairType> storage;
public:
void extract(std::vector<std::string> &result)
{
result.resize(storage.size());
std::transform(storage.begin(), storage.end(), result.begin(), boost::bind(&PairType::get<0>, _1));
}
};

int main(int argc, char**argv)
{

TestClass<int> bb;
std::vector< std::string> result;
bb.extract(result);
return 0;
}

g++ test.cpp
test.cpp: In member function `void TestClass<T>::extract(std::vector<std::string, std::allocator<std::string> >&)':
test.cpp:17: error: expected primary-expression before ',' token
test.cpp: In member function `void TestClass<T>::extract(std::vector<std::string, std::allocator<std::string> >&) [with T = int]':
test.cpp:26: instantiated from here
test.cpp:17: error: address of overloaded function with no contextual type information

最佳答案

使用成员版本的get 和Boost.Bind。我已经对此进行了测试,它确实有效,物有所值。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>

int main()
{
typedef boost::tuple<std::string,int> T;
std::vector<T> v1;
v1.push_back(T("Blah", 23));
v1.push_back(T("Wibble", 9));

std::vector<std::string> v2;
std::transform(v1.begin(), v1.end(), std::back_inserter(v2), boost::bind(&T::get<0>, _1));

std::copy(v2.begin(), v2.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

return 0;
}

关于c++ - boost 元组+变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4675930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com