Reputation: 1950
std::map< std::string, std::vector<std::string> > families;
// add new families
families["Jones"];
families["Smith"];
families["Doe"];
// add children
families["Jones"].push_back( "Jane" );
families["Jones"].push_back( "Jim" );
I added the values to vector within the map using above method. How can I check if "Jane" exists in map with key "Jones"?
Upvotes: 0
Views: 2789
Reputation: 24324
Just check if given surname is in your map
and then use std::find
. I am not using auto
, as from the comments I believe you may not be using C++11-compatible compiler.
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
bool exists(std::map<std::string, std::vector<std::string> >& families,
std::string& name, std::string& surname) {
if(families.find(surname) == families.end()) return 0;
std::vector<std::string> names = families[surname];
return std::find(names.begin(), names.end(), name) != names.end();
}
int main(int argc, char* argv[]) {
std::map<std::string, std::vector<std::string> > families;
// add new families
families["Jones"];
families["Smith"];
families["Doe"];
// add children
families["Jones"].push_back("Jane");
families["Jones"].push_back("Jim");
std::string name("Jane"), surname("Jones");
bool ex1 = exists(families, name, surname);
std::cout << ex1 << std::endl;
return 0;
}
Upvotes: 1
Reputation: 9733
Use the find member function of std::map for this and after that a regular string search:
std::map<std::string, std::vector<std::string> >::const_iterator search = families.find("Jones");
if(search != families.end())
{
std::vector<std::string> s = search->second;
if (std::find(s.begin(), s.end(), "Jane") != s.end())
{
}
}
Upvotes: 5
Reputation: 106096
Here's an example:
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
int main()
{
std::map< std::string, std::vector<std::string> > families;
// add new families
families["Jones"];
families["Smith"];
families["Doe"];
// add children
families["Jones"].push_back( "Jane" );
families["Jones"].push_back( "Jim" );
auto family_iterator = families.find("Jones");
if (family_iterator != families.end())
{
const std::vector<std::string>& family = family_iterator->second;
if (std::find(family.begin(), family.end(), "Jane") != family.end())
std::cout << "found\n";
}
}
Basically, families.find()
searches in a map
and returns an iterator
, for which ->first
is the key you've found and ->second
is the value: your value is the std::vector<std::string>
for the "Jones"
family, and for convenience/concision I create a const
reference to it.
To search in vector
I use std::find()
from <algorithm>
.
Code available/runnable here
Upvotes: 1