从 unordered_map 内的向量中删除元素

问题描述

在我的课堂上,我有一个无序的向量映射,如下所示:

std::unordered_map<State,std::vector<std::shared_ptr<const City>>> citiesByState;

我的类也有这两个方法

  void addCity(State state,const std::shared_ptr<const City>& city);
  void removeCity(State state,const std::shared_ptr<const City>& city);

添加一个城市,如下所示:

void Manager::addCity(State state,const std::shared_ptr<const City>& city) {
  auto location = citiesByState.find(state); // Find the state in the map
  if (location == citiesByState.end()) { // If the state isn't in the map
    std::vector<std::shared_ptr<const City>> cities; // Create a vector
    cities.push_back(city); // Add the city
    citiesByState[state] = cities; // Add the state and city vector to my map
  } else {
    auto vector = location->second; // Get the city vector. If the city isn't there already,add it.
    if (std::find(vector.begin(),vector.end(),city) == vector.end()) {
      vector.push_back(city);
    }
  }
}

在这是我删除城市的代码

void Manager::removeCity(State state,const std::shared_ptr<const City>& city) {
  auto location = citiesByState.find(state);
  if (location != citiesByState.end()) {
    auto vector = location->second;
    if (vector.size() > 0) {
      std::cout << "Vector isn't empty." << std::endl;
    }
    vector.clear(); // Just empty it out for Now.
  }
}

然后我像这样运行它:

  City city = ... // get city
  manager->addCity(State::NewYork,city);
  manager->removeCity(State::NewYork,city);

我可以重复调用 manager->removeCity(State::NewYork,city),每次我看到向量都不为空。好像无法从 Vector 中移除。

我做错了什么?

解决方法

TL;DR

您是从向量的副本中删除元素,而不是从 std::vector 的找到的 location 中存在的 std::unordered_map 中删除元素。

长话

当您在 auto vector = location->second; 中调用 Manager::removeCity 时,您是在 if 语句的范围内制作该向量的副本。因此,您的更改不会反映在您定位的容器中。只有您的副本会受到影响,并且在 if 语句结束时也超出范围,因此如果您找到 location 发生的所有事情都不会保存在 {{ 1}} 容器。

您可以通过直接调用 std::unordered_map 来解决此问题,或者,如果您真的想给它另一个名称,请使用引用,例如location->second.clear()。请注意,这也适用于 auto& vec = location->second; vec.clear(); 方法。

附言为了避免混淆,我将避免使用与容器或 STL 中完善的类相同的变量名。