0

Let's say I have the following poc code:

const string& a = "hello";
string b = "l";

if(a.at(2) == b)
{
 // do stuff
} 

I understand that there is no operator "==" that matches these operands. And, the way to fix it is by converting the value of the variable a into 'hello' (instead of double quotes) as char.

However, what if I have no choice but performing the comparison as shown in the code. Is it possible? Could you please provide any guidance or suggestions you might have on this issue.

Your responses are appreciated.

Xigma
  • 177
  • 1
  • 11

2 Answers2

4

You're comparing a char (to be specific a const char) and a std::string, of which there exists no overloaded comparison operator for (operator==).

You have some options:

(1) compare b's first character to the character you're wanting to compare to

string b = "l";
string a = "hello";
if(a[2] == b[0]) { /* .. */ }

(2) convert a[2] to a std::string

string b = "l";
string a = "hello";
if(string{a[2]} == b) { /* .. */ }

(3) let b be a char

char b = 'l';
string a = "hello";
if(a[2] == b) { /* .. */ }

Also, you should not construct a string object like this

const string& a = "hello";

unless you actually want to create a reference to another string object, e.g.

string x = "hello";
const string& a = x;
miguel.martin
  • 1,626
  • 1
  • 12
  • 27
  • Thank you for the detailed breakdown of those options. In my code, I'm actually passing "const string& a" as a function argument. – Xigma Dec 21 '17 at 00:28
1
const string& a = "hello";
string b = "l";

if (a[2] == b[0])
{
    // do stuff
}

a.at(2) is not string. when do b to b[0] problem solving.

RequireBool
  • 48
  • 1
  • 6