Home > Back-end >  is there a way to use the ternary operator with arrays?
is there a way to use the ternary operator with arrays?

Time:05-16

I was trying to write an algorithm that would take 2 numbers as input and output them in ascending order using the ternary operator but on line 20:24 it tells me: "error: invalid array assignment". Can someone help me? many thanks in advance.

#include <iostream>

using namespace std;

int main()
{
     int a, b;
     int c[2];
     int d[2];
     int e[2];
     cout << "inserire il primo numero: ";
     cin >> a;
     cout << "inserire il secondo numero: ";
     cin >> b;

     c[0] = b;
     c[1] = a;
     d[0] = a;
     d[1] = b;
     e = (a > b) ? c : d;
     cout << e;
}

CodePudding user response:

as long as the left side has the appropriate = operator, you can write this statement. C-Style arrays do not have this as you try to change their pointer. read more.

you can use std::array<int, 2>, which has the operator= and offers many benefits (read more):

#include <iostream>
#include <array>

int main() {
    int a, b;
    std::array<int, 2> c;
    std::array<int, 2> d;
    std::array<int, 2> e;

    std::cout << "inserire il primo numero: ";
    std::cin >> a;
    std::cout << "inserire il secondo numero: ";
    std::cin >> b;

    c = { b, a };
    d = { a, b };

    e = (a > b) ? c : d;

    for (auto& i : e) {
        std::cout << i << ' ';
    }
}

read here why you shouldn't use namespace std;.

CodePudding user response:

Ternay operator works fine. In your code, the problem was in assigning the array. You can't assign an array like that.

One of the ways you can follow:

#include <iostream>

using namespace std;

int main()
{
     int a, b;
     int c[2];
     int d[2];
     int e[2];
     cout << "inserire il primo numero: ";
     cin >> a;
     cout << "inserire il secondo numero: ";
     cin >> b;

     c[0] = b;
     c[1] = a;
     d[0] = a;
     d[1] = b;
     (a > b) ? memcpy(e, c, sizeof c) : memcpy(e, d, sizeof d);

     cout << e[0] << " " << e[1] << endl;
}

Please check the below URL to learn more ways for assigning one array to another other than running a loop.

How to assign values of array to another array(making copy)

  • Related