-2

Why I can't compile the code bellow?

string m = "MEOW";
pair <string, int> p = { "M", 0 };
if (m[0] == p.first)
   p.second += 10;

I get the error:

main.cpp:18:14: error: invalid operands to binary expression ('int' and 'std::__1::basic_string<char>')
    if (m[0] == p.first)
        ~~~~ ^  ~~~~~~~
Jeffy
  • 71
  • 1
  • 5

2 Answers2

2

p.first is a string. m[0] is a char. You cannot compare those two types.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Even if I explicitly specify `(char)p.first`? – Jeffy Sep 01 '19 at 15:03
  • @Jeffy how would casting a `string` to a `char` ever make any sense? A string is *not* a char. A cast is not magic. It can only convert sensibly between types that are convertible to eachother. If not, you just get garbage (Undefined Behaviour). – Jesper Juhl Sep 01 '19 at 15:11
0

I try to compare m[0] as a new string object and it works:

string m = "MEOW";
pair <string, int> p = { "M", 0 };
if (string(1, m[0]) == p.first)
   p.second += 10;
Jeffy
  • 71
  • 1
  • 5
  • This is very different from what you initially posted. Here you are *creating* a new string from a char, then comparing two string objects. – Jesper Juhl Sep 01 '19 at 15:17
  • @JesperJuhl yes, I understand. Most likely I incorrectly formulated the question. – Jeffy Sep 01 '19 at 15:52