3

I have two maps, tk1 and tk2 with the following structure:

std::map<std::string, double>tk1;
std::map<std::string, double>tk2;

tk1 contains the following data:

    2011-01-03 2200
    2011-01-04 2209
    2011-01-05 2300

and tk2 contains the following data:

2011-01-03 2450
2011-01-04 2465
2011-01-06 2476
2011-01-07 2457

I have created a set that contains the dates as strings as in

std::set<std::string>dateset;
std::set<std::string>new_dateset;

I created it by iterating through the 2 maps and inserting into the set as in

dateset.insert(it->first);

dateset has the following values:

2011-01-03
2011-01-04
2011-01-05
2011-01-06
2011-01-07

I want to populate new_dateset so it only contains the dates that are in both tk1 and tk2, i.e. new_dateset should contain only

2011-01-03
2011-01-04

I wrote the following:

std::set<std::string>::iterator it1=dateset.begin(), end1=dateset.end();
std::map<std::string, double>::iterator it2=tk1.begin(), end2=tk1.end();
std::map<std::string, double>::iterator it3=tk2.begin(), end3=tk2.end();
while (it1 != end1) {
if (it2->first == *it1) 
new_dateset.insert(it2->first);
++it1;
}

but obviously I am not doing it correctly. Can someone suggest the best way to do this.

user1155299
  • 877
  • 5
  • 20
  • 29

4 Answers4

3

You might consider std::set_intersection with the key_iterator from a previous answer.

Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • The dates are the keys of a `std::map`, so they are already sorted. – Alan Stokes May 12 '12 at 17:28
  • Good point -- I sort of knew that, then my memory quit working, and I edited the "If you can depend..." into it, even though it didn't make any real sense. Thanks for reminding me of reality! :-) – Jerry Coffin May 12 '12 at 17:31
1

Iterate over it1, check if first for each element is in tk2 using the find() method, and insert it into the set if it is there. What you are doing in your example is to check elements in dataset, which contain keys that are in tk1 OR tk2.

for(; it2 != end2; ++it2) {
  if(tk2.find(it2->first) != end3) new_dataset.insert(it2->first);
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

You should compare strings as follows:

if(it2->first.compare(*it) == 0)
{
  //strings match, do something.
}
else
{
  // no match do something else.
}
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
0

Iterate over elements in tk1 and see if the keys exist in tk2. If it does, then insert.

for(; it2 != end2; ++it2)
{
  if(tk2.find(it2->first) != end3)
  {
    new_dataset.insert(it2->first);
  }
}
Vikas
  • 8,790
  • 4
  • 38
  • 48