【问题标题】:C++: inserting into a boost::unordered_map from key and value vectorsC++:从键和值向量插入到 boost::unordered_map
【发布时间】: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/…

标签: c++ map insertion


【解决方案1】:

你很接近。在上面的示例中, 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));
}

【讨论】:

  • 我不知道为什么我的编辑没有通过;上面需要两个更正:将“double”更改为“string”,将“”。
  • 其实有几个错误或者错别字。我相信应该是m_map.insert(make_pair(t.get&lt;0&gt;(),t.get&lt;1&gt;()));map_insertor(stringmap &amp;m) : m_map(m); 也出现错误 - 想要 '{' 而不是 ';'。
猜你喜欢
  • 1970-01-01
  • 2021-01-22
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2015-05-24
  • 2016-09-19
相关资源
最近更新 更多