InsaneCoder
InsaneCoder

Reputation: 8288

Error inserting string key,value in unordered_map

I am writing my first STL program in C++, and I am facing this issue.

This is my program :

#include <iostream>
#include <unordered_map>

using namespace std;

int main()
{
    int n,m;
    // n : number of file extenstions
    // m : number of filenames to identify
    string extension, type, filename;
    cin >> n >> m;

    unordered_map<string,string> hashmap;

    while(n--)
    {
        cin >> extension >> type;
        hashmap.insert(make_pair<string,string>(extension,type));
    }
    while(m--)
    {
        cin >> filename;
        extension = filename.substr(filename.find_last_of('.')+1);
        cout << extension << endl;
    }
}

My input file is :

5 6
html text/html
htm text/html
png image/png
svg image/svg+xml
txt text/plain
index.html
this.file.has.lots.of.dots.txt
nodotsatall
virus.exe
dont.let.the.png.fool.you
case.matters.TXT

I am getting error : no matching function for call to ‘make_pair(std::string&, std::string&)’ . I cannot figure out the problem.

Upvotes: 2

Views: 374

Answers (2)

skypjack
skypjack

Reputation: 50568

First of all, I'd rather use make_pair(extension, type) and let the compiler to deduce the types in any case, to avoid any risks, as someone else suggested.

Anyway, I see that the details below are interesting from your point of view, thus it's worth to put them in a dedicated response, hoping they are also right.

That said, see the documentation.

As far as I understand (I'm far from being an expert) the deduced types in your case would be T&, U&, thus using the couple T, U (as <string, string>) ends in a function prototype that doesn't accept references as arguments (that's why you got the error and that one specifically).

You can use instead the following pattern in your case:

make_pair<string&,string&>(extension,type)

This one works for you actually use references to initialize the pair and you are going to require the sames as template arguments.

Again, for the make_pair can easily deduce the types of its arguments, you can freely omit them and I strongly suggest to do that.

Upvotes: 0

therainmaker
therainmaker

Reputation: 4343

The error is in the line

make_pair<string,string>(extension,type)

It should instead be

make_pair(extension, type)

Upvotes: 2

Related Questions