0

I am trying to take a std::pair and map it to a std::string using a std::map. The way it works being given a pair consisting of a char and a string, map it to a particular string.

This setup so far works just fine(compiler accepts it):

std::map<std::pair<char, std::string>, std::string> mymap;
std::map<std::pair<char, std::string>, std::string>::iterator it;

But when i try to do this:

mymap['a', "Q1"] = "Q4";
mymap['b', "Q2"] = "Q3";
mymap['c', "Q3"] = "Q2";
mymap['d', "Q4"] = "Q1";

it comes back as this error which I do not understand:

Error   1   error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const char [3]' (or there is no acceptable conversion)

which is the error associated under the left bracket of each of the four lines of code(where a red squiggly appears)

can someone help me to understand what I am doing wrong?

1
  • 2
    Do it like mymap[{'a', "Q1"}] = "Q4"; Commented Mar 29, 2017 at 4:39

2 Answers 2

2

The [] operator on map doesn't take two items. It takes just one. In your case it's expecting a std::pair object. So something like this will work:

mymap[std::pair<char, std::string>('c', "Q1")] = "Q4";

You might want to make a typedef for your pair class:

using myPair = std::pair<char, std::string>;
mymap[myPair('c', "Q1")] = "Q4";
Sign up to request clarification or add additional context in comments.

Comments

1

the [] operator for the std::map accepts only one argument, whereas you provided two. Since you want to use an object of type std::pair, you should make an std::pair object with your char and std::string. You can do it by enclosing them in {}:

mymap[{'a', "Q1"}] = "Q4";
mymap[{'b', "Q2"}] = "Q3";
mymap[{'c', "Q3"}] = "Q2";
mymap[{'d', "Q4"}] = "Q1";

You could also provide an object definition each time you try yo access the elements:

mymap[std::pair<char, std::string>('a', "Q1")] = "Q4";
mymap[std::pair<char, std::string>('b', "Q2")] = "Q3";
mymap[std::pair<char, std::string>('c', "Q3")] = "Q2";
mymap[std::pair<char, std::string>('d', "Q4")] = "Q1";

But the first option in my opinion is better and less errorprone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.