Combining Map and C ++ String Array

I am writing code to check whether a person has visited a place before or not, if the truth does nothing, add a new place to the list of visited places. I use a map to store the student’s name as a key and an array of storage, as shown below.

#include<map> using namespace std; map<string,string[]> stu_plac; map<string,string[])::iterator it; 

I could not find a way to search on the map

I tried the following:

 bool exist=false; if(stu_plac.count(name)) { it=stu_plac.find(name); for(auto tt=(*it).second.begin(); tt!=(*it).second.end(); tt++) { if (tt.compare(place)==0)//exist { exist=true; } break; } if (!exist) { (*it)second[++tt]=place; } } else { stu_plac.insert(pair<string,string[]>(name,place)); } 

I think the problem is with the array of string iterator, can you help me find the right way to do this. Do I need to use a multi-mast or other data structure for this?

+4
source share
4 answers

A data structure such as map<string, vector<string> > will work.

You can use for (size_t i = 0; i < it->second.size(); i++) to move the vector.

+5
source

It looks like you need a line map β†’ places

 typedef map<string,std::set<string> > Map; 

Adapting it for your fragment (which had a lot of problems, starting with confusing formatting ...):

 #include<map> #include<set> #include<string> using namespace std; typedef map<string,std::set<string> > Map; typedef Map::iterator It; int main() { bool exist=false; Map stu_plac; string name = "name"; string place = "0.0.0.0"; It it = stu_plac.find(name); if (stu_plac.end() != it) { std::set<string>& visits = it->second; exist = visits.end() != visits.find(place); if (!exist) visits.insert(place); } } 

But actually you may prefer to use std::multimap

+4
source

I do not use an array because I cannot know its size, I prefer to use a vector or list, and instead of using a boolean variable, I would insert and then interrupt the loop, so my algorithm would be similar

  std::map<std::string, std::list<std::string> > stu_plac; std::map<std::string, std::list<std::string> >::iterator it; std::string myName("Edu"); std::string myPlace("Madrid"); 

.....

 for( it = stu_plac.begin(); it != stu_plac.end(); it++){ if(it->first == myName){ std::list<std::string>::iterator place = std::find(it->second.begin(), it->second.end(), myPlace); if(place == it->second.end()){ it->second.push_back(myPlace); break; } } } 

See that you can use an iterator to add the city you want.

By the way, I would not use the auto variable if it is not C ++ 11.

+1
source

An array in C ++ is one of the types or constructs inherited from C, so the built-in "type" array has no iterators. It also does not track the current size, so you cannot start and end iterators of an array without preserving its size.

Use std::map< std::string, std::vector<std::string> > instead.

0
source

Source: https://habr.com/ru/post/1439970/


All Articles