Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor similar to std::map or std::vector in a class

I'm creating a class and I want to know how to create a constructor similar to the std::map or std::vector style.

std::map<std::string, std::string> map = {
    {"foo", "bar"},
    {"biz", "buz"},
    {"bez", "boz"}
};

The difference is that I don't want my class to ask for types that wants to accept, just like std::map does.

std::map<std::string, std::string>

I want my class to accept that style of arguments:

{
    {"foo", "bar"},
    {"biz", "buz"},
    {"bez", "boz"}
};

But with defined type. (std::string, Typer)

The 'Typer' is a class that I will insert as value on the std::map.

like image 972
SH.0x90 Avatar asked Feb 21 '14 15:02

SH.0x90


People also ask

What can I use instead of map in C++?

One alternative would be to use flat_map from Boost. Containers: that supports the same interface as std::map , but is backed by a sorted contiguous array (think std::vector ) instead of a tree.

What is the difference between vector and map in C++?

A vector has constant time lookup, while std::map is usually implemented as a RB tree, which has a O(log n) look-up time, and even a hash map (such as TR1 unordered_map) usually has a worse complexity, because the index (or a hash thereof) will be mapped to a bucket that can contain multiple values.

Does map have a copy constructor?

Copy constructor is used to copy a whole existing map and the map to be copied is passed as a single param to the constructor.

Can C++ map have vector?

In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.


2 Answers

If I understand your question correctly, you want a constructor taking std::initializer_list<std::pair<std::string, Typer>>, like this:

struct Typer
{
  std::string data;

  Typer(const char *s) : data(s) {}
};


struct MyClass
{
  MyClass(std::initializer_list<std::pair<std::string, Typer>> i)
    : myMap(begin(i), end(i))
  {}

  std::map<std::string, Typer> myMap;
};

int main()
{
  MyClass m = {
    {"foo", "bar"},
    {"biz", "buz"},
    {"bez", "boz"}
  };
}

Live example

like image 190
Angew is no longer proud of SO Avatar answered Oct 22 '22 08:10

Angew is no longer proud of SO


typedef std::map<std::string, Typer> MyType;

like image 24
Lightness Races in Orbit Avatar answered Oct 22 '22 07:10

Lightness Races in Orbit