1

我有两个std::vector<std::string>。一个包含字段名称;另一个包含相应的值。将所有字段名/值对插入 boost::unordered_map 的最佳方法是什么?

我当然可以在向量上获得两个迭代器并循环遍历,在每次迭代中插入一对,但我想知道是否有更简单的方法。

更新 1:附加信息:我有g++ 4.4,所以我无法访问大多数 c++11 的好东西。

更新 2:根据@chris 的建议,我正在尝试使用boost::iterator. 这是我正在使用的 Boost 文档中的示例:

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?

4

1 回答 1

2

你很亲密。在上面的示例中, zip_func 是您提供的函子,它可以完成您想要的工作。在这种情况下,类似于:

typedef unordered_map<string,string> stringmap;

struct map_insertor {
    void operator()(const boost::tuple<const string&, const string&> &t ) {
        m_map.insert(make_pair(t.get<0>(),t.get<1>());
    }
    map_insertor(stringmap &m) : m_map(m) {}
    private:
        stringmap &m_map;
};

stringmap my_map;
for_each( 
    boost::make_zip_iterator(
        boost::make_tuple(beg1, beg2)
    ),
    boost::make_zip_iterator(
        boost::make_tuple(end1, end2)
    ),
    map_insertor(my_map)
);

但是简单的解决方案没有任何问题。

typedef vector<string> stringvec;

stringvec::iterator ik = vec_of_keys.begin();
stringvec::iterator iv = vec_of_vals.begin();
for( ;(ik != vec_of_keys.end()) && (iv != vec_of_vals.end()); ik++,iv++) {
  my_map.insert(make_pair(*ik, *iv));
}
于 2013-08-09T22:47:26.137 回答