std::unordered_map with class data

I'm trying to make an unordered_map with a key of std::string and a data type of my own class, "Variable". This is my code that I've done:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>

class Variable {        // The class that I want to have as data type
    public:
        Variable(double value) : _value(value) {}

        double getValue(void) const { return _value; }
        void setValue(double v) { _value = v; }

        bool operator== (const Variable &rhs) {
            return this->_value == rhs._value;
        }

    private:
        double _value;
};

int main() {
    std::unordered_map<std::string, Variable> VarMap;       // My map of "Variable"s

    // Initialising a variable "x" with value 65
    std::pair<std::string, Variable> tempVariable ("x", 65);
    std::pair<std::unordered_map<std::string, double>::iterator, bool>
        result = VarMap.insert(tempVariable);

    // Printing the values
    if (result.second) {
        std::cout << "New Variable: " << (result.first)->first << std::endl;
        std::cout << "Variable Value: " << (result.first)->second << std::endl;
    }

    return 0;
}


This code works just fine when I use double instead of "Variable", but the moment I put in the class "Variable" instead it gives my this massive error:

(cut for clarity)\main.cpp|25|error: conversion from 'std::_Hashtable<std::basic_string<char>, std::pair<const std::basic_string<char>, Variable>, std::allocator<std::pair<const std::basic_string<char>, Variable> >, std::_Select1st<std::pair<const std::basic_string<char>, Variable> >, std::equal_to<std::basic_string<char> >, std::hash<std::basic_string<char> >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, true, false, true>::_Insert_Return_Type {aka std::pair<std::__detail|

Does anyone know what I can do to fix this? Thanks.
Last edited on
unordered_map requires operator!= as well.

See
http://www.cplusplus.com/reference/unordered_map/unordered_map/operators/
I'm still getting the same error, having added in the following to my "Variable" class:

1
2
3
bool operator!= (const Variable &rhs) {
    return this->_value != rhs._value;
}
ok, I see. The errror occurs on line 26:

std::pair<std::unordered_map<std::string, double>::iterator, bool> // wrong type
Thanks, that fixed it!
Topic archived. No new replies allowed.