【问题标题】:Trying to print an unordered_map尝试打印 unordered_map
【发布时间】:2016-03-18 18:12:46
【问题描述】:

我正在编写一个简单的程序来查找字谜。我正在使用一个哈希表,其中已排序的字符串作为键,未排序的字符串作为值。当我尝试打印 unordered_map (散列图)时,它给了我这个错误。

错误 1 ​​错误 C2675: 一元 '++' : 'std::string' 没有定义这个 运算符或转换为预定义可接受的类型 运算符 c:\program files (x86)\microsoft visual studio 12.0\vc\include\xhash 672 1

#include <iostream>
#include <list>
#include <cstdlib>
#include <map>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <cstring>



void Anagrams(std::vector<std::string> &v){

    std::unordered_map<std::string, std::string> wordTable;

    char sortedString[256];

    for (std::string tmp : v){

        strcpy(sortedString, tmp.c_str());

        std::sort(sortedString, sortedString + tmp.size());

        std::string backToString(sortedString);

        wordTable.insert(backToString, tmp);
    }

    std::cout << "Map contains" << std::endl;


    std::cout << "mymap's buckets contain:\n";
    for (unsigned i = 0; i < wordTable.bucket_count(); ++i) {
        std::cout << "bucket #" << i << " contains:";
        for (auto local_it = wordTable.begin(i); local_it != wordTable.end(i); ++local_it)
            std::cout << " " << local_it->first << ":" << local_it->second;
        std::cout << std::endl;
    }




}




int main()
{

    std::vector<std::string> words{ "debitcard", "badcredit", "cat", "act", "evils", "elvis" };

    Anagrams(words);



    return 0;


}

由于某种原因,它认为迭代器“local_it”是一个字符串。有人可以帮忙吗?

【问题讨论】:

  • char sortedString[256]; 为什么要使用 char 数组?只需使用std::string
  • 好点。我没有意识到这一点。谢谢

标签: c++ iterator hashmap anagram


【解决方案1】:

问题在于std::unorderd_map::insert() 函数采用std::pair&lt;key, value&gt;,而不是key, value

 wordTable.insert(std::make_pair(backToString, tmp));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2023-01-20
    • 1970-01-01
    • 2013-12-16
    • 2017-08-31
    • 2016-01-18
    • 1970-01-01
    • 2022-11-20
    相关资源
    最近更新 更多