2

我只能使用 C++98 并且无法访问std::map::at()C++11 添加的实现。

我的目标是编写一个at()行为类似于std::map::at().

因此,我编写了以下非成员函数:

template<typename K, typename V>
V& at(std::map<K, V> map, K key)
{
  if (map.find(key) == map.end())
    throw std::out_of_range("key not found");
  return map.find(key)->second;
}

我至少可以看到一个问题,即我的版本表现得好像我返回了一份副本(见下文)。

std::map<int,int> myMap;
myMap.insert(std::pair<int,int>(2,43));

// myMap.at(2)=44;            // modifies the reference
// assert(44==myMap.at(2));   // fine 

at(myMap,2)=44;               // does not modify the value inside the map, why?
assert(44==myMap.at(2));      // not fine
  1. 我该如何解决这个问题?
  2. 我的包装还有其他问题吗?
4

3 回答 3

10

主要问题是您正在调用未定义的行为。

at按值获取地图:

V& at(std::map<K, V> map, K key)

所以你要返回一个对本地对象中一个项目的引用,这是非常未定义的。

您应该使用参考:

V& at(std::map<K, V>& map, const K& key)

您可能还想添加 const 版本:

const V& at(const std::map<K, V>& map, const K& key)
于 2013-10-24T13:31:14.767 回答
2

将签名更改为

V& at(std::map<K, V>& map, K key)
于 2013-10-24T13:30:32.653 回答
1

您的方法中有两个问题:

  • 您将地图实例作为值传递,因此不仅复制整个地图,而且还返回对该本地副本中元素的引用并生成 UB
  • 你做了两次查找,这在地图上是相当昂贵的操作

所以你的代码可能是:

template<typename K, typename V>
V& at(std::map<K, V> &map, K key)
{
   std::map<K,V>::iterator f = map.find(key);
   if ( f == map.end())
     throw std::out_of_range("key not found");
   return f->second;
}
于 2013-10-24T13:35:29.947 回答