用于std :: map :: at()的C++ 98 Wrapper

ToB*_*oBe 2 c++ stl c++11

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

我的目标是编写一个非成员函数at()函数(使用C++ 98),其行为类似于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;
}
Run Code Online (Sandbox Code Playgroud)

我至少可以看到一个问题,那就是我的版本表现得好像我已经返回了一个副本(见下文).

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
Run Code Online (Sandbox Code Playgroud)
  1. 我该如何解决这个问题?
  2. 我的包装器还有其他问题吗?

mol*_*ilo 10

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

at按值获取地图:

V& at(std::map<K, V> map, K key)
Run Code Online (Sandbox Code Playgroud)

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

你应该使用一个参考:

V& at(std::map<K, V>& map, const K& key)
Run Code Online (Sandbox Code Playgroud)

您可能还想添加const版本:

const V& at(const std::map<K, V>& map, const K& key)
Run Code Online (Sandbox Code Playgroud)

  • 那,并命名一个`std :: map`实例`map`只是一种可怕的形式...... (4认同)