Reputation: 147
I want to 'manage' flights, using map<string, set<string>>
. The string
keys represents the flight number while the set<string>
values represent the people's name registered onto the flight. In my case, I read data from a simple text file such as:
123 jhonny
132 harry
123 bill
145 herry
132 jarry
in order to find the people in the same flight.
I know that a basic way to insert into a map is
map<string, string> m;
m["hi"] = test;
and using the iterator to read the container.
But how can I insert and read the composition of a set into a map?
I tried with a double iterator, or using the while and a iterator to take data from a file:
string pers, volo;
while (wf >> volo >> pers) {
m[volo] = pers;
}
but it gives error.
I'm new in STL and I've read some files, guide, and others to learn sets and maps, but I haven't found anything about container composition (such as the one I've described). How can I do that? Perhaps with a double iterator on map and on set?
Thank you.
Upvotes: 2
Views: 78
Reputation: 8987
Just treat your m[volo]
like any kind of regular set. Your set
will be default-constructed once you access its value using std::map::operator[]
. This allows you to directly use any of set
's member functions. To add a value to the set, use std::set::insert
.
Here's what your code might look like using standard input/output:
string a, b;
while (cin >> a >> b) {
m[a].insert(b);
cout << m[a].size() << endl;
}
If you want to output your set, a convenient way to do this would be to define an overload over operator<<
. The following defines a template any set.
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& s)
{
for (auto& el : s)
os << el << ' ';
return os;
}
This allows you to do the following without any errors.
for (auto it = m.begin(); it != m.end(); ++it)
{
cout << it->first; // a string
cout << ' ';
cout << it->second; // a set
cout << endl;
}
Upvotes: 3