0

Edit: This question does not already have an answer, especially when you link the wrong question. I was asking why giving 2 parameters, specifically to a std::vector bracket, only used the last parameter. I did NOT ask why you can't overload brackets with more than one parameter. Please, do you research if you're going to say I haven't done mine.

I was surprised to find that when I put multiple numbers in brackets, they only used the last number to work with:

int main()
{
    std::vector<int> input = { 1,2,3 };
    std::cout << input[1, 2, 3, 1];

    return 0;
}

output:

2

Are the previous numbers being ignored, and can I use them when I overload the brackets?

  • 3
    That's the comma operator in action, see cppreference.com. The comma simply has a different meaning in the first and second line. – Ulrich Eckhardt Mar 29 '22 at 06:47
  • @UlrichEckhardt Oh so do you mean that the comma just tells the program to point to the next item, but in this context only the last one is evaluated for the brackets? – Pupper Gump Mar 29 '22 at 06:51
  • @PupperGump Change that to `std::cout << input[2, 1, 3, 1];` -- What gets printed? – PaulMcKenzie Mar 29 '22 at 06:52
  • No. I just wanted to give you the name "comma operator" for further research, plus a reference where you can read the definition. Any better textbook should cover that thing though. – Ulrich Eckhardt Mar 29 '22 at 06:53
  • Note that in [C++23](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2128r6.pdf), it is planned to support multidimensional indexing with this syntax. – prapin Mar 29 '22 at 06:53
  • @PaulMcKenzie 2 – Pupper Gump Mar 29 '22 at 07:06
  • `std::cout << (1,2,3,4,1) << '\n';` should be pretty educational, especially as you start rearranging the numbers in the sequence between test runs, and particularly if you [enable heightened warnings](https://godbolt.org/z/Yrc14Yh38). – WhozCraig Mar 29 '22 at 07:11
  • you can write nice trick code with commas. – user1095108 Mar 29 '22 at 09:11

0 Answers0