Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert object into std::map while declaration

Question:

I'm trying to insert instance of a class into std::map at compile time but getting the below error always.

main.cpp:18:12: error: ‘_info’ was not declared in this scope
     _info(1)
        ^

line number 18 points to below block of the code

15. std::map<std::string, Info > lookup  {
16.      {
17.        "aclk",
18.        _info(1)
19.      }
20.    };

Code:

#include <random>
#include <iostream>
#include <functional>
#include <map>

class Info{
    int _info;
public:
   Info(int info){
     _info = info;
   }   
}; 


 std::map<std::string, Info > lookup  {
  {
    "aclk",
    _info(1)
  }
};

int main()
{
   //dummy
}

Observation:

When I dynamically create the object I don't see any such errors.

const std::map<std::string, Info > lookup  {
  {
    "aclk",
    new Info(1)
  }
};

But map being const and instance being inserted with new doesn't make any sense.

like image 337
kiran Biradar Avatar asked Jul 24 '26 11:07

kiran Biradar


1 Answers

You have to supply an object of the type Info instead of its data member _info. For example

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    1
  }
};

This is valid because the class Info has a conversion constructor.

Or (if for example the constructor is explicit)

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    Info(1)
  }
};
like image 94
Vlad from Moscow Avatar answered Jul 27 '26 02:07

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!