是否有任何内置的哈希图函数来处理 c++ 中的值输入?



这是我输入的txt文档:

Hello A:1
World A:1
Hello A:2
World A:2
Hello B:1
World B:2
Hello C:4

我试图在哈希图中像循环哈希图一样使用它对我没有帮助。这是我对哈希表的键和值:

String word,word1,word2,word3,word4; // for example word1 is Hello, word2 is A:1
size_t sub1;
word = word1 + word2;   
sub1 = word.find(":");
word3 = word.substr(0,sub1+1); //word3 = "Hello A" which is my key for internal hash function 
word4 = word.substr(sub1+1,word.length()); //word4 = 1,2 which is word3's value.

您知道我可以使用哪个内置函数来获取此输出吗?

Hello A:1,2 B:1 C:4
World A:1,2 B:2

显然有更好的解决方案,如果您给我一些想法,最好是一些代码,我将不胜感激?

假设冒号前的字符始终是 A-Z 之间的单个大写字符,并且输出行的顺序并不重要,则可以使用此解决方案。

int main() {
  std::unordered_map<std::string, std::vector<std::string>> mmap;
  std::string line;
  std::stringstream stream;
  while (std::getline(file, line)) {
    stream.str(line);
    std::string word;
    stream >> word;
    if (mmap.find(word) == mmap.end()) {
      mmap[word] = std::vector<std::string>(26);
    }
    char letter, sep;
    int num;
    stream >> letter >> sep >> num;
    std::string& entry = mmap[word][letter - 'A'];
    if (entry.empty())
      entry += std::to_string(num);
    else
      entry += "#" + std::to_string(num);
    stream.clear();
  }
  for (auto const& [word, record] : mmap) {
    std::cout << word << " ";
    const char* sep1 = "";
    for (size_t i = 0; i < record.size(); i++) {
      if (!record[i].empty()) {
        std::cout << sep1 << char(i + 'A') << ":";
        stream.str(record[i]);
        char const* sep2 = "";
        std::string num;
        while (std::getline(stream, num, '#')) {
          std::cout << sep2 << num;
          sep2 = ",";
        }
        sep1 = " ";
      }
      stream.clear();
      stream.str("");
    }
    std::cout << std::endl;
  }
}

如果顺序很重要,您只需将unordered_map更改为 map

最新更新