以字符串向量作为值的哈希映射

hashMap with string vector as values

本文关键字:哈希 映射 字符串 向量      更新时间:2023-10-16

我正在尝试使用带有字符串向量作为值的C++映射,但不确定我是否使用正确的语法将字符串插入向量中。请查看下面的代码:

我还尝试了以下方法: hashMap.insert(sortedWord).push_back(words[i]);

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

void groupAnagrams(string words[])
{
    int i=0;
    map <string, vector<string> > hashMap;
    for(i=0;i<10;i++) {
        cout<<words[i]<<endl;
        string sortedWord = words[i];
        sort(sortedWord.begin(),sortedWord.end());
        cout<<"Sorted: "<<sortedWord<<endl;
        hashMap[sortedWord].push_back(words[i]);
    }
    return;
}
int main()
{
    string words[10] = {"weed","act","cat","tac","tea","eat","ate","bat","mat","tab"};
    groupAnagrams(words);
    return 1;
}

我得到的错误是:

groupAnagrams.cpp:23:22: error: implicit instantiation of undefined template 'std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >'
                hashMap[sortedWord].push_back(words[i]);
                                   ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/iosfwd:200:28: note: template is declared here
class _LIBCPP_TEMPLATE_VIS vector;
                           ^
In file included from groupAnagrams.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/iostream:38:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/ios:216:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/__locale:15:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/string:477:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/string_view:176:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/__string:56:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
/Library/Developer/CommandLineTools/usr/include/c++/v1/utility:321:9: error: implicit instantiation of undefined template 'std::__1::vector<std::__1::basic_string<char>,
      std::__1::allocator<std::__1::basic_string<char> > >'
    _T2 second;
        ^

您必须包含向量标头:

#include <vector>