-1

Ddoes any body know how do do this? Thanks if you do. I am new in c++. I don't know what do do. Python is much better in my opinion.

#include <bits/stdc++.h>
using namespace std;
int main(){
    int nums[] = {1, 2, 3, 4};
    if (nums == [1, 2, 3, 4]){
        cout<<1;
    }
}
  • 1
    Tip: Don't use `#include ` as it's highly non-portable. Also avoid `using namespace std` as the `std::` prefix serves an important purpose. – tadman Nov 13 '20 at 23:39
  • Is `==` a situation where arrays decay to pointers? I know you can't compare raw arrays using `==`, but I'm not sure what exact mechanism actually is occurring under the hood. – Nathan Pierson Nov 13 '20 at 23:47
  • That code won't even compile. `[1,2,3,4]` is not a valid syntax for expressing an array in C++. In any event, raw arrays like `nums` cannot be compared directly, because they decay to pointers, so comparing them `array1 == array2` only tests if their first element has the same address. Either write a loop that compares elements one at a time, or use a standard container (`std::array`, `std::vector`, etc) to hold the elements. Those containers are part of the standard library, and do support being compared as you wish. – Peter Nov 13 '20 at 23:53
  • And, if you think Python is better, then use Python, rather than complaining that C++ does not do things like Python. C++ and Python are different languages, with different purposes. And each does some things better than the other. – Peter Nov 13 '20 at 23:55
  • And neither can make a decent burger. Depending on your immediate needs that can make both Python and C++ utterly worthless. – user4581301 Nov 14 '20 at 00:27

2 Answers2

3

You should use std::array instead of plain arrays to realize this.

#include <iostream>
#include <array>

int main(void) {
    std::array<int, 4> nums = {1, 2, 3, 4};
    if (nums == std::array<int, 4>{1, 2, 3, 4}){
        std::cout<<1;
    }
}

Also see:

MikeCAT
  • 61,086
  • 10
  • 41
  • 58
0

From C++17, you can use class template argument deduction to simplify MikeCAT's solution like this:

std::array nums = {1, 2, 3, 4};
if (nums == std::array{1, 2, 3, 4}) {
    std::cout << 1;
}
cigien
  • 50,328
  • 7
  • 37
  • 78