0

I don't know what it is that I'm missing. It looks simple enough, but has eluded me for a couple days.

I've tried five or six ways to initialize an unordered map, getting the same error every time.

Data Structures

#include <unordered_map>

using namespace std;

struct InStruct{

    InStruct(char readchr, int currentState) {
        this->readchar = readchr;
        this->currentState = currentState;
    }

    InStruct() = default;
    InStruct(InStruct&) = default;

    char readchar;
    int currentState;
};

struct OutStruct {

    OutStruct(char writechar, bool moveleft, int newstate) {
        this->writechar = writechar;
        this->moveleft = moveleft;
        this->newstate = newstate;
    }

    OutStruct() = default;
    OutStruct(OutStruct&) = default;

    char writechar;
    bool moveleft;
    int newstate;
};

Main:

int main() {
    const unordered_map<InStruct, OutStruct>& turingmap {
        std::make_pair(InStruct('B', 1), OutStruct('B', false, 5)),
        std::make_pair(InStruct('a', 1), OutStruct('B', false, 2)),
        std::make_pair(InStruct('a', 2), OutStruct('a', false, 2)),
        std::make_pair(InStruct('b', 2), OutStruct('b', false, 2)),
        std::make_pair(InStruct('B', 2), OutStruct('B', true, 3)),
        std::make_pair(InStruct('b', 3), OutStruct('B', true, 2)),
        std::make_pair(InStruct('a', 4), OutStruct('a', true, 4)),
        std::make_pair(InStruct('b', 4), OutStruct('b', true, 4)),
        std::make_pair(InStruct('B', 4), OutStruct('B', false, 1))
    };
    return 0;
}

Error C2440 'initializing': cannot convert from 'initializer list' to 'const std::unordered_map,std::equal_to<_Kty>,std::allocator>> &' TuringMachine c:\users\apaz\source\repos\turingmachine\turingmachine\source.cpp 152

apaz
  • 9
  • 1
  • 3
    Do you have a `std::hash` defined for `InStruct`? That's mandatory if you want to use it as key in an `std::unordered_map`. (In this case, it's not the initializer list itself which caused the problem but what is contained in it.) – Scheff's Cat Apr 20 '19 at 15:45
  • Not sure why you'd make a reference there, but whatever. Your `unordered_map` is likely the problem, not how you're trying to initialize it. Try just declaring an empty one. Your structs have no hash function. – Retired Ninja Apr 20 '19 at 15:45
  • This might be interesting: [SO: How to specialize std::hash::operator() for user-defined type in unordered containers?](https://stackoverflow.com/a/8157967/7478597) – Scheff's Cat Apr 20 '19 at 15:47
  • You need to do something like this: https://ideone.com/HZOHNn Was going to write an answer, but no time ATM and hopefully this gets you on the right track. Good luck! – Retired Ninja Apr 20 '19 at 16:17

0 Answers0