Hi

I come from Python background and learning C++. In one of my programs, I need to have one key with multiple values and both being strings.

for e.g.

"str1" ---> "value of str1" 
"str2" ---> "value of str2" 
"str1" ---> "value of str1 1"
"str1" ---> "value of str1 2"

I think I need something like this:

map<string, vector<string> > mymap

My question is how do I iterate and insert?

Thanks and sorry for n00b question

How do you intend to use this?

Why wouldn't a simple std::vector<std::string> be sufficient?

I would check the multimap container.

http://www.cplusplus.com/reference/stl/multimap/

Hi Gerard4143,

Thanks. I already implemented something like that. Here:

class outgoing
{
	multimap<string, string> outGoing;
	public:
	void add(string a, string b)
	{
		
		 outGoing.insert(pair<string, string>(a, b));
	 }
	 
	 void iter()
	 {
		 
		for (multimap<string, string>::iterator it = outGoing.begin();
       it != outGoing.end();
       ++it)
   cout << "  [" << (*it).first << ", " << (*it).second << "]" << endl;
}
 };

Code compiles fine, works fine. But when I iterate it shows like this:

str1 --> value1
str1 ---> value2
str2   -> value

How do I count number of values/attributes for a particular key? for e.g. in this case, it would be 2 for str1?

How do you intend to use this?

Why wouldn't a simple std::vector<std::string> be sufficient?

Sorry if I was not clear, it is for a graph in which a node can have multiple edges.

So is it your intent to create data pairs, then count the number of data pairs that contain a specific first value?

EDIT: NVM, overlapped....

The multimap class includes a function, called equal_range, which returns the range (as iterator pair) of elements of the multimap that have the same key. Finding the number of elements with the same key is simply a matter of counting the elements in that range.

If your purpose is to construct a graph of some kind, you might want to take a look at the Boost.Graph Library (BGL) which has all sorts of graph / tree containers and algorithms.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.