Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

拥有2个string 类型变量的自定义 struct,作为std::unordered_map的key

  1. User

    拥有2个string 类型变量的自定义 struct,作为std::unordered_map的key

  2. Assistant

    可以将这两个string类型变量作为一个pair的形式来作为std::unordered_map的key,例如:

    #include <unordered_map>
    #include <string>
    
    struct MyStruct {
        std::string str1;
        std::string str2;
    };
    
    bool operator==(const MyStruct& a, const MyStruct& b) {
        return a.str1 == b.str1 && a.str2 == b.str2;
    }
    
    // 使用一个pair作为MyStruct的hash函数
    struct MyStructHasher {
        std::size_t operator()(const MyStruct& s) const {
            return std::hash<std::string>()(s.str1) ^ std::hash<std::string>()(s.str2);
        }
    };
    
    std::unordered_map<MyStruct, int, MyStructHasher> my_map; // 定义一个以MyStruct为键的unordered_map
    

    这里使用了自定义的hash函数MyStructHasher,将两个字符串的hash值进行异或操作,得到一个表示MyStruct的唯一hash值。同时还重载了等于运算符,让MyStruct可以比较是否相等。这样就可以使用MyStruct类型作为std::unordered_map的键了。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.