Finding elements of a set in a map

I have two maps: tk1and tk2with 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 tk2contains the following data:

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

I created a set containing dates as strings, as in

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

I created it, iterating through 2 maps and inserting into a set, as in

dateset.insert(it->first);

dateset has the following meanings:

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 dates that are in both tk1and tk2that is, new_dateset should only contain

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'm doing it wrong. Can someone suggest a better way to do this.

+3
source share
4 answers

it1, , first tk2, find(), , . - dataset, , tk1 tk2.

for(; it2 != end2; ++it2) {
  if(tk2.find(it2->first) != end3) new_dataset.insert(it2->first);
}
+1

std::set_intersection key_iterator .

+3

:

if(it2->first.compare(*it) == 0)
{
  //strings match, do something.
}
else
{
  // no match do something else.
}
0

tk1 , tk2. , .

for(; it2 != end2; ++it2)
{
  if(tk2.find(it2->first) != end3)
  {
    new_dataset.insert(it2->first);
  }
}
0

All Articles