I've been trying to make a very simple map container and I thought it would be nice to be able to initialize it like so:
Hash table = { "name1" >> value,
"name2" >> value2,
"name3" >> value3,
"name4" >> value4 };
How I was going to go about this was by first making a pair(duo) data structure which would keep the name and the value of each element, overload the >> operator to return a duo using the name and value parameters and make a constructor for the hash class to initialize it by using the initializer_list to construct a vector of the duo elements.Then use binary search methods to retrieve the wanted element.
Unfortunately I hit a wall from the very start. Before I started coding everything I wanted to make sure that the overloads were used correctly and in fact it was a smart decision since apparently they are not.
This works:
#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>
struct duo {
duo(const std::string key,int value) :key(key) ,value(value) {};
const std::string key;
int value;
};
struct Hash {
std::vector<duo> lister;
Hash(std::initializer_list<duo> passed) :lister(passed) {};
};
duo operator >> (const std::string& id,int value) {
return duo(id,value);
}
int main(){
duo object1("test",1);
Hash table = {object1};
std::cout << table.lister[0].key << table.lister[0].value;
}
but this gives "invalid operands of types ‘const char [6]’ and ‘int’ to binary ‘operator>>’"
#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>
struct duo {
duo(const std::string key,int value) :key(key) ,value(value) {};
const std::string key;
int value;
};
struct Hash {
std::vector<duo> lister;
Hash(std::initializer_list<duo> passed) :lister(passed) {};
};
duo operator >> (const std::string id,int value) {
return duo(id,value);
}
int main(){
Hash table = {"test1" >> 1};
std::cout << table.lister[0].key << table.lister[0].value;
}
I tried to pass std::string to the >> operator because I can't overload with primitive types. It seems this is not a solution though. Is there any way to achieve the desired effect without explicitly converting the string literals to std::string ?