【发布时间】:2021-03-14 09:17:00
【问题描述】:
在我的课堂上,我有一个无序的向量图,如下所示:
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 中删除。
我做错了什么?
【问题讨论】:
-
您尝试使用
const std::shared_ptr<const City>&类型访问无序映射中的值,其中映射的键类型为State,在citiesByState.find(city)行中。也许你想要的是citiesByState.find(state)? -
@D-RAJ 这是一个错字。我正在按州找到它,但问题仍然存在。
标签: c++ c++11 stdvector unordered-map