EuLaur D
EuLaur D

Reputation: 21

Comparison behavior of ' <' operator

Why is this printing "Popescu" instead of "Ionescu", since "Popescu" > "Ionescu"?

#include <iostream>

using namespace std;

int main(){

    char v[3][100] = {"Popescu","Ionescu","Vasilescu"};
    if(v[0]<v[1]){
        cout << v[0];
    }else{
        cout << v[1];
    }
    return 0;
}

Upvotes: 2

Views: 69

Answers (2)

Rahul_Patil
Rahul_Patil

Reputation: 145

Your Initialization is wrong that is why print 'Popescu'

First You need to clear about your array position that is main criteria before start work on your program see my image

see below example:

char always take one character:

#include <iostream>

using namespace std;

int main(){

    char v[3][3] =
    {
     {'p','I','l'},
     {'s','e','r'},
     {'q','w','x'}
    };

    cout<< v[0][0];  //print the array2d 

    return 0;
}

output:

p

First Condition:

#include <iostream>

using namespace std;

int main(){

    char v[3][100] = {"p","I","l"};    

    if(v[0][0]==v[0][0])
    {
        //cout << v[0]; //when uncomment this line output is p
        cout << v[1];  **see here print the i because check the position of array image**
    }
    else 
    {
        cout << v[1];
    }
    return 0;
}

output: I //now the position of your array see below

enter image description here

Now the second Condition:

int main(){

    char v[3][100] = {"p","I","l"};    

    if(v[1]==v[1])
    {
        // cout << v[0];
        cout << v[1];   
    }
    else
    {
        cout << v[1];
    }
    return 0;

output: I

If the above criteria Understood then Come To your main problem:

#include <iostream>

using namespace std;

int main(){

    char v[3][100] = {"p","I","l"};    

    if(v[0]<=v[1])
    {
        cout << v[0];
        // cout << v[2];
    }
    else
    {
        cout << v[1];
    }
    return 0;
}

output: p

I hope my answer is understood.

Upvotes: 1

MSalters
MSalters

Reputation: 179779

Since char[100] doesn't have an operator<, you fall back to operator< for char*. That was not what you intended - it returns the first object in memory. And v[0] definitely precedes v[1].

You want std::string, where operator< is overloaded to do what you want.

Upvotes: 5

Related Questions