Reputation: 31
I have the following statement in a file x.cpp. Suppliers and location are classes I created. If I write in my main.cpp
Suppliers s;
s.clean_up();
and in file x.cpp
void Suppliers::clean_up(){
for(auto i : setter){
i.second.clear();}}
Setter is a public data member of Suppliers
map<std::string,std::vector<location>> setter
The map is not cleared when I try to print it. On the contrary if I have the following in my main, the values in my map are cleared as I would expect.
Suppliers s;
for (auto item : s.setter){
item.second.clear();}
I have no Compiler errors, in one case the location vector is erased and in one case it isn't. The only thing I can think of is that the instance of setter aren't the same. But because I'm using a method I can't see why this wouldn't work. Any help would be great, thanks in advance!
Upvotes: 1
Views: 74
Reputation: 117886
You should iterate using references to your map items
for(auto& i : setter)
{
i.second.clear();
}
Otherwise i
will be a copy of each std::pair<std::string, std::vector<location>>
. So it will clear()
the vector of the copy, not the actual instance in the map
.
Upvotes: 6