是否可以进行以下操作。
假设我的 boost 元组有<std::string, T>
我想使用 std::transform + mem_fun 仅在相应的向量中插入 std::string 元素。是否可能或者我们需要使用循环和push_back(get)...
即以下内容不喜欢编译...(未知类型...)
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)