在map中的vector中查找值&lt; string,<vector <string>&gt;在c ++中

时间:2015-09-25 06:07:16

标签: c++ string dictionary vector

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" );

我使用上面的方法将值添加到地图中的矢量。如何检查“Jane”中是否存在“Jane”?

3 个答案:

答案 0 :(得分:3)

为此使用std :: map的find成员函数,之后进行常规字符串搜索:

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())
  {
  }
}

答案 1 :(得分:1)

以下是一个例子:

#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";
    }
}

基本上,families.find()map中搜索并返回iterator->first是您找到的密钥,->second是值:您的值是std::vector<std::string>系列的"Jones",为了方便/简洁,我创建了一个const引用。

要在vector中进行搜索,我使用std::find()中的<algorithm>

代码可用/可运行here

答案 2 :(得分:1)

只需检查您的姓氏是否在map中,然后使用std::find。我没有使用auto,因为我认为您可能没有使用与C ++ 11兼容的编译器。

#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;
}