0

这是我的输入 txt 文档:

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

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

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

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

4

1 回答 1

0

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

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_mapmap

于 2019-11-23T16:52:38.463 回答