Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi, I have a list of tuples named "c" and a map of list of tuples named "map1". i want to add the tuples of list to special elements in map. for example, i want to add tuple{1,2} to map1[0]. the code I wrote is as follow:
C++
list<std::tuple<int, int>> l = list<std::tuple<int, int>>();
	auto it=c.begin();
	while(c.size()>k)
	{
		tuple<int, int> f=it._Ptr[0]._Myval;
		int seed=std::get<0>(f);
		int Dseed=std::get<1>(f);
	        Cmerge=find_nearest_group(Dseed);
		int Cnew= costof_new_group(Dseed,k);
		if(Cmerge<Cnew)
		{
			l.push_back(make_tuple(seed, Dseed));
			map1[PMerge] = l;
			c.remove(f);
		}
		else
		{
			create_new_group(seed,k);
			for(int i=0;i<k;i++)
			{				
				tuple<int, int> f=it._Ptr[0]._Myval;
			
				std::advance(it, 1);
				c.remove(f);
			}
		}
		
	}
C++



the problem is when the while loop repeats, the "l" clears and it clears the tuples exist in map and replace the new tuple into the element of map. for example, if the tuples exist in map1[0] are {3,2},{4,5]} and in the next repeat the tuple in l is {3,6}, it replace {3,2} and {4,5} with {3,6} in map1[0]. but i want to add the new tuple to the old tuples. how can i resolve the problem?

What I have tried:

i defined the "l" list as global to avoid being clear, but it was not helpfull
Posted
Updated 19-Apr-17 10:30am

1 solution

I think your problem is the statement map1[PMerge] = l;. If map1[PMerge] already has a value, it replaces that value with your new list l. You can't use the subscript notation for this problem. You have to use map::find() and map::insert().

find() returns an iterator to a map element, which is a pair<int, list>, or it returns end(). If the iterator == end(), you need to add a pair<int, list> to the map. If the iterator != end(), it already points to a pair<int, list>. You need to push a tuple onto the existing list, given by foundit->second.

C++
auto foundit = map1.find(PMerge);
if (foundit == map1.end())
{
    map1.insert(make_pair(PMerge, l));
}
else
{
    foundit->second.push_back(make_tuple(seed, Dseed));
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900