【问题标题】:boost lib, unordered set with c++ is giving me a headacheboost lib,用 c++ 设置的无序集让我头疼
【发布时间】:2012-12-08 07:30:54
【问题描述】:

好的,我知道这可能会很容易,但我有这段代码实现了 boost 库(这是我第一次使用它),我似乎无法让它正常工作。这是代码。 哈希.h

#include .....
#include "boost/unordered_set.hpp"
#ifndef HASH_H
#define HASH_H

class hash{
public:
    int toHash(string);
    void insertKey(string);
    bool lookupKey(string);
private:
    string hashTable[];
    vector<string> vfile;
    typedef boost::unordered_set<std::string, int> um;
struct hashkey{
    string state;
    int stateno;
};

};

#endif  /* HASH_H */

还有 hash.cpp

#include <boost/unordered/unordered_set.hpp>
#include "hash.h"

int hash::toHash(string key){
    unsigned int x;
    std::stringstream ss;
    ss << std::hex << key;
    ss >> x;
    return x;
}

void hash::insertKey(string key){
    um.insert(key,toHash(key));
}

bool hash::lookupKey(string key){
    return um.find(key)==um.end();
}

我收到“hash.cpp:18:7: error: expected unqualified-id before ‘.’ token”。我重申,我知道这可能很容易,我只是以前没有使用过 boost 库。我查看了互联网上的许多示例,但我似乎无法让这个“简单”的部分起作用。谢谢。

【问题讨论】:

  • 吹毛求疵,但您的标头包含保护应该包装整个文件,否则您可能会多次包含同一个文件(如果它没有适当的标头包含保护)。

标签: c++ boost unordered-set


【解决方案1】:

您的um 不是成员变量,而是类型定义。去掉 typedef 关键字。

现在关于你的第二个问题......

摆脱你的哈希计算成员方法和模板的第二个参数。摆脱 insert() 的第二个参数。 boost unordered_set 已经为许多标准类型提供了散列函数,包括 std::string。但是,如果要散列用户定义的类型,则需要提供散列函数,但不是以您在此处执行的方式。您将创建一个名为 hash_value() 的函数的重载,如下所示:

std::size_t hash_value(yourUserDefinedType_probablyAClassName const &t) 
{
    std::size_t retValue;
    //...compute your hash however you want & store in retValue....
    return retValue;
} 

【讨论】:

  • 不。如果我删除 typedef 我得到: hash.cpp:18:30: error: no matching function for call to 'boost::unordered::unordered_set<:basic_string>, int>::insert(std::string& , int)'
  • @crazy_pants - 好的,这是一个单独的问题。我也编辑了我的答案来解决这个问题。
【解决方案2】:

你使用 typedef 来声明一个类型。 um 是一种类型,而不是变量。从你的代码中移除 typedef,或者声明一个 um 类型的变量。

【讨论】:

  • 不,如果我说....h 'code' um um2;然后 .cc 'code' um2.insert(key,toHash(key));我得到了一大堆错误。比如,'code' hash.cpp:18:31: error: no matching function for call to 'boost::unordered::unordered_set<:basic_string>, int>::insert(std::string&, int )'天哪,为什么这不理解代码格式?!?!?!
  • @crazy_pants - 在 cmets 中,将代码放在反引号 like this 之间,它将保留您输入的原始字符。
  • 那么再说一遍......如果我说不......h um um2; then .cc um2.insert(key,toHash(key)); 我得到了一大堆错误。喜欢,hash.cpp:18:31: error: no matching function for call to ‘boost::unordered::unordered_set&lt;std::basic_string&lt;char&gt;, int&gt;::insert(std::string&amp;, int)
  • 编译器似乎在告诉你信任。 Unordered_set 确实没有这样的 insert 方法。它想要值,而不是值的散列;该集合将为自己计算哈希。见the documentation
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
相关资源
最近更新 更多