【问题标题】:Adding two maps together将两张地图加在一起
【发布时间】:2012-06-16 08:02:02
【问题描述】:

我想将两个地图与以下行为一起添加。

如果键存在 -> 将两个键值相加。

如果键不存在 -> 插入对到映射。

我查看了一些标准库算法。即转换,但似乎没有做我想要的。

取自LINK

template < class InputIterator, class OutputIterator, class UnaryOperator >
  OutputIterator transform ( InputIterator first1, InputIterator last1,
                             OutputIterator result, UnaryOperator op )
{
  while (first1 != last1)
    *result++ = op(*first1++);  // or: *result++=binary_op(*first1++,*first2++);
  return result;
}

我的想法是,在使用时我的第二张地图中只有一个迭代器和适当的仿函数

 *result++=binary_op(*first1++,*first2++);

因此,我将无法遍历我的第二张地图来查找键值。

一个想法只是让我自己的算法稍作改动。

template < class InputIterator, class ContainerType, class BinaryOperator >
  void myTransform ( InputIterator first1, InputIterator last1,
                               ContainerType cont2,  
                               BinaryOperator binary_op )
{
  while (first1 != last1)
    binary_op(first1++, cont2); //cont2 passed by reference 
}

然后我就可以使用了:

cont2.find() 在我的函子中搜索整个地图。

这将是我所想的一个更​​完整的示例,但我似乎遇到了一个我无法解决的编译错误(我有点猜测 BinaryOperator 类型......见下文)?

#include <map>
#include <string>
#include <iostream>

template < class InputIterator, class ContainerType, class BinaryOperator >
void myTransform ( InputIterator first1, InputIterator last1,
                 ContainerType &cont2, 
                 BinaryOperator binary_op )
{
  while (first1 != last1)
    binary_op(first1++, cont2); //cont2 passed by reference
}

template<class IteratorType, class ContainerType>
struct AddMapValues:
  std::binary_function<IteratorType, ContainerType, void>
{
  void operator()(IteratorType itr, ContainerType& cont)
  {
    if( cont.find(itr->first) != cont.end() ) cont[itr->first] = cont.find(itr->first).second + itr->second;
    else cont.insert( (*itr) );
  }
};


int main()
{
  typedef std::map<std::string, double> stringDoubleMap;
  typedef std::map<std::string, double>::iterator stringDoubleMapItr;
  typedef void (*ptrfnt)(stringDoubleMapItr, stringDoubleMap& );

  stringDoubleMap map1;
  stringDoubleMap map2;

  map1.insert( stringDoubleMap::value_type("Test1",1.0) );
  map1.insert( stringDoubleMap::value_type("Test2",2.0) );
  map1.insert( stringDoubleMap::value_type("Test3",3.0) );

  map2.insert( stringDoubleMap::value_type("Test1",1.0) );
  map2.insert( stringDoubleMap::value_type("Test2",2.0) );
  map2.insert( stringDoubleMap::value_type("Test3",3.0) );

  myTransform( map1.begin(), map1.end(),
               map2, 
               AddMapValues< stringDoubleMapItr, stringDoubleMap >() );

  return 0;

}

这是我的编译器错误:

testingMapTransforms.cxx: In function ‘int main()’:

testingMapTransforms.cxx:52:85: error: no matching function for call to     ‘myTransform(std::map<std::basic_string<char>, double>::iterator, std::map<std::basic_string<char>, double>::iterator, stringDoubleMap&, std::map<std::basic_string<char>, double>::iterator, AddMapValues<std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, double> >, std::map<std::basic_string<char>, double> >)’

testingMapTransforms.cxx:52:85: note: candidate is:

testingMapTransforms.cxx:12:20: note: template<class InputIterator, class ContainerType, class   OutputIterator, class BinaryOperator> OutputIterator myTransform(InputIterator, InputIterator,  ContainerType, OutputIterator, BinaryOperator)

似乎有另一个迭代器来自某个地方,并且容器类型没有正确读取?

有什么想法吗?

我正在使用

gcc - GNU 项目 C 和 C++ 编译器

Ubuntu/Linaro 4.6.3-1ubuntu5

谢谢

注意:

我已在答案中更新了上述代码的工作版本。如果您认为我应该更改问题代码,请告诉我。不确定最佳做法

【问题讨论】:

  • 你有什么理由不能手工做吗?
  • 我认为您在一行中执行了许多操作; *result++ = op(*first1++); 这样的代码很难调试,可读性也不是很好。
  • @Spo1ler 完全同意。让编译器完成其工作优化,而不是编写代码,以便其他人可以阅读。
  • @Daniel Daranas 我希望我的代码灵活(不要过多地依赖于类型)并且高效。 for 循环将是一个简单的解决方案,但不是我正在寻找的,因为我正在尝试学习“不同”技术。

标签: c++ gcc ubuntu gnu


【解决方案1】:

您的代码不可读。很容易出错。

手工操作,但一次只做一件事。不要混合递增指针、取消引用它们、将元素添加到地图和从另一个地图查询都在同一行中。结果一团糟。

【讨论】:

  • 我同意这段代码不是最易读的,但我从标准库中的 transform 中获取了代码库,所以我的想法是这将是 transform 算法的最佳编码实践。无论如何,我的编译错误来自我的模板调用。
  • @MWright:实现的规则和用户代码的规则不同。
【解决方案2】:

这是上面的修改版本。问题代码中有很多错误,但这似乎可行并且是相同的想法:

template < class InputIterator, class ContainerType, class BinaryOperator >
void myTransform ( InputIterator first1, InputIterator last1, ContainerType &cont2, BinaryOperator binary_op )
{
  while (first1 != last1)
    (*binary_op)(first1++, cont2); //cont2 passed by reference
}

template<class IteratorType, class ContainerType>
struct AddMapValues:
  std::binary_function<IteratorType, ContainerType, void>
{
  static void Add(IteratorType itr, ContainerType& cont)
  {
    cont[itr->first] += itr->second;
  }
};

int main()
{

  typedef std::map<std::string, double> stringDoubleMap;
  typedef std::map<std::string, double>::iterator stringDoubleMapItr;
  typedef void (*ptrfnt)(stringDoubleMapItr, stringDoubleMap& );

  stringDoubleMap map1;
  stringDoubleMap map2;

  map1.insert( stringDoubleMap::value_type("Test1",1.0) );
  map1.insert( stringDoubleMap::value_type("Test2",2.0) );
  map1.insert( stringDoubleMap::value_type("Test4",3.0) );

  map2.insert( stringDoubleMap::value_type("Test1",1.0) );
  map2.insert( stringDoubleMap::value_type("Test2",10.0) );
  map2.insert( stringDoubleMap::value_type("Test3",3.0) );

  myTransform( map1.begin(), map1.end(), map2, AddMapValues<stringDoubleMapItr, stringDoubleMap >::Add );

  for(stringDoubleMapItr itr = map2.begin(); itr != map2.end(); ++itr ){
    std::cout << "INFO: Key: " << itr->first << " | Value: " << itr->second  << std::endl;
  }

  return 0;

}

【讨论】:

    【解决方案3】:
    I want to add two maps together with the following behavior:
    If key exists add two key values together.
    If key does not exist. Insert pair to map.
    

    我认为一个简单的 for 循环可以满足您的需求:

    for(auto it = map2.begin(); it != map2.end(); ++it) map1[it->first] += it->second;
    

    如果键存在,则将值添加到现有键中。如果键不存在,operator[] 将插入它,它的值将被默认初始化(double 为 0.0)。

    我认为在这里使用适用于任何容器的通用函数是不明智的。 say vector 和 map 的 insert() 和 operator[] 的语义差别太大了。

    【讨论】:

    • @jrok myTransform 模板的想法将用于地图或矢量,并将使用您提供的任何函子。 AddMapValues 函子显然只适用于地图。
    【解决方案4】:

    我认为你不能用transform 做到这一点。你有两个容器, 你需要两个迭代器对,你需要推进它们 当一个元素仅在其中一个中时,分别。两个序列 transform 的版本同步推进它们。

    手工操作应该不会太难。像下面这样的东西, 也许:

    typedef std::map<std::string, std::double> Map
    
    Map
    addValues( Map const& m1, Map const& m2 )
    {
        Map results;
        Map::const_iterator i1 = m1.begin();
        Map::const_iterator i2 = m2.begin();
        while ( i1 != m1.end() && i2 != m2.end() ) {
            if ( i1->first < i2->first ) {
                results.insert( results.end(), *i1 );
                ++ i1;
            } else if ( i2->first < i1->first ) {
                results.insert( results.end(), *i2 );
                ++ i2;
            } else {
                results.insert( results.end(),
                                Map::value_type( i1->first, i1->second + i2->second ) );
                ++ i1;
                ++ i2;
            }
        }
        results.insert( i1, m1.end() );
        results.insert( i2, m2.end() );
        return results;
    }
    

    (在制作模板之前,我会先让它像这样工作。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 2022-12-11
      • 2010-11-07
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多