1

I'm not sure if this has been asked before, or my wording is incorrect, but I'm unable to assign variable values on to a map.

How should I change my variables/map/(other?) to allow for adding variables values to a map?

#include <iostream>
#include <map>
#include <string>
using namespace std;

map<string, int> int_map;

int main() {
    //this is okay
    int_map.insert(make_pair<string, int>("three", 3));
    
    string three = "three";
    int num = 3;
    
    //but this isn't
    int_map.insert(make_pair<string, int>(three, num));
    
    return 0;
}

This is the online IDE I used to run the code above: https://ideone.com/fork/7ZurUs

The error is:

prog.cpp: In function ‘int main()’:
prog.cpp:16:50: error: no matching function for call to ‘make_pair<std::__cxx11::string, int>(std::__cxx11::string&, int&)’
  int_map.insert(make_pair<string, int>(three, num));
                                                  ^
In file included from /usr/include/c++/8/bits/stl_algobase.h:64,
                 from /usr/include/c++/8/bits/char_traits.h:39,
                 from /usr/include/c++/8/ios:40,
                 from /usr/include/c++/8/ostream:38,
                 from /usr/include/c++/8/iostream:39,
                 from prog.cpp:1:
/usr/include/c++/8/bits/stl_pair.h:524:5: note: candidate: ‘template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)’
     make_pair(_T1&& __x, _T2&& __y)
     ^~~~~~~~~
/usr/include/c++/8/bits/stl_pair.h:524:5: note:   template argument deduction/substitution failed:
prog.cpp:16:40: note:   cannot convert ‘three’ (type ‘std::__cxx11::string’ {aka ‘std::__cxx11::basic_string<char>’}) to type ‘std::__cxx11::basic_string<char>&&’
  int_map.insert(make_pair<string, int>(three, num));
                                        ^~~~~
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    Use `make_pair("three", 3)` and `make_pair(three, num)` instead, [let it deduce the templates for you](https://stackoverflow.com/questions/9641960/). But, there is a much simpler way - use `map::operator[]` instead: `int_map[three] = num;` – Remy Lebeau Nov 16 '21 at 23:57
  • also, the error you're getting incorporates a C++11 feature explicitly! if you actually compiled this in C++98 mode, you'd not get an error. But that's just because c++98 doesn't "understand" you're abusing `make_pair`: As Remy said, you mustn't specify the template types! – Marcus Müller Nov 16 '21 at 23:59
  • @RemyLebeau Got it! I'll implement that. Thank you for your help! – Kenneth Chen Nov 17 '21 at 01:12
  • @MarcusMüller Ah, I see! I'm primarily a Java developer I think I've been using a lot of the "techniques" that Java has on its language. Thank you for that clarification! – Kenneth Chen Nov 17 '21 at 01:14

0 Answers0