C++ 从无序映射中的向量中删除元素
在我的课堂上,我有一个无序的向量图,如下所示:C++ 从无序映射中的向量中删除元素,c++,c++11,stdvector,unordered-map,C++,C++11,Stdvector,Unordered Map,在我的课堂上,我有一个无序的向量图,如下所示: std::unordered_map<State, std::vector<std::shared_ptr<const City>>> citiesByState; void Manager::addCity(State state, const std::shared_ptr<const City>& city) { auto location = citiesByState.find
std::unordered_map<State, std::vector<std::shared_ptr<const City>>> citiesByState;
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);
}
}
}
City city = ... // get city
manager->addCity(State::NewYork, city);
manager->removeCity(State::NewYork, city);
我可以反复调用manager->removeCity(State::NewYork,city)
,每次我都看到向量不是空的。似乎我无法从向量中移除
我做错了什么;DR
您正在从向量的副本中删除元素,而不是从std::unordered_映射的找到的位置中存在的std::vector
中删除元素
说来话长
当你调用autovector=location->second
在Manager::removeCity
中,您正在if
语句范围内复制该向量。因此,您的更改不会反映在目标容器中。只有您的副本会受到影响,并且在if
语句结束时,这也超出了范围,因此,如果您找到位置
发生的所有事情都不会保存在std::unordered_map
容器的状态中
您可以通过直接调用location->second.clear()
来解决这个问题,或者,如果您真的想给它起另一个名字,可以使用引用,例如auto&vec=location->second;向量清除()代码>。请注意,这也适用于Manager::addCity
方法
另外,为了避免混淆,我不会使用与STL中容器或已建立的类相同的变量名。您试图使用const std::shared\u ptr&
类型访问无序映射中的值,其中映射的键类型为行中的State
citiesByState.find(城市)
。也许你想要的是citiesByState.find(state)
?@D-RAJ那是个打字错误。我是按州来找的,但问题仍然存在。这正是问题所在。如此琐碎却又如此容易错过。谢谢你,先生!
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);