【发布时间】:2013-08-10 23:55:03
【问题描述】:
我有两个std::vector<std::string>。一个包含字段名称;另一个包含相应的值。将所有字段名/值对插入 boost::unordered_map 的最佳方法是什么?
我当然可以在向量上获得两个迭代器并循环遍历,在每次迭代中插入一对,但我想知道是否有更简单的方法。
更新 1:附加信息:我有 g++ 4.4,所以我无法访问大多数 c++11 好东西。
更新 2:根据@chris 的建议,我正在尝试使用boost::iterator。这是我正在使用的示例from the Boost documentation:
std::vector<double>::const_iterator beg1 = vect_of_doubles.begin();
std::vector<double>::const_iterator end1 = vect_of_doubles.end();
std::vector<int>::const_iterator beg2 = vect_of_ints.begin();
std::vector<int>::const_iterator end2 = vect_of_ints.end();
std::for_each(
boost::make_zip_iterator(
boost::make_tuple(beg1, beg2)
),
boost::make_zip_iterator(
boost::make_tuple(end1, end2)
),
zip_func()
);
A non-generic implementation of zip_func could look as follows:
struct zip_func :
public std::unary_function<const boost::tuple<const double&, const int&>&, void>
{
void operator()(const boost::tuple<const double&, const int&>& t) const
{
m_f0(t.get<0>());
m_f1(t.get<1>());
}
private:
func_0 m_f0;
func_1 m_f1;
};
我了解zip_func() 的定义。 struct 应该住在哪里?它应该返回任何东西吗?为什么会有operator()?那里发生了太多事情,我无法理清头绪。对于我的问题,zip_func() 如何提取字段名称和值并将其插入unordered_map?
【问题讨论】:
-
不要引用我的话,但是
boost::zip_iterator? -
这看起来很有希望。我仍然必须显式循环,但它更好地封装了这对迭代器(并声称有更好的性能)。查看示例:boost.org/doc/libs/1_41_0/libs/iterator/doc/…