2

I have the following program:

#include <iostream>
using namespace std;

int main()
{
    int array[] = {1, 2, 3};
    int a = array[0],
        b = array[1],
        c = array[2];

    cout << c << endl;
}

This prints 3, so far so good. But I wonder if there is a more elegant syntax for declaring multiple variables from an array at once. For example (just an idea, does not compile):

int [a, b, c] = array;

Is there any feature like this in C++ or one of the new standards? I can't be the only one looking it.

Alternatively: what is your most elegant way to set multiple variables from an array at once?

4
  • I think it would be nice to tell us more what you want to do with those variables or what do you to do after that Commented Jul 6, 2017 at 19:47
  • 2
    As you've specified c++11, i'd take a look at std::tie Commented Jul 6, 2017 at 19:48
  • 1
    Is there a reason you cannot use the array directly? Is an array really the most appropriate structure for your actual problem? Arrays are intended for a list of items. If the data is instead a collection of related data, a class or struct is more appropriate. Commented Jul 6, 2017 at 19:50
  • Depends: In my project I have a data array to begin with (different author). But in general I agree, a struct would have been the better choice obviously. Commented Jul 6, 2017 at 20:01

2 Answers 2

7

In C++17 you can use structured bindings - their syntax is very similar to what you have posted:

auto [a, b, c] = array;

live example on wandbox


The closest thing to that in C++11/14 is std::tie, but it unfortunately doesn't work with arrays: it only supports std::tuple. You could however use metaprogramming to create an utility that creates a tuple from an array, and then use tie on it. There's a possible implementation in this answer by W.F..

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that was fast! Good to see this is actually coming. Now let's hope the C++17 standard is finalized fast. :)
3

What you are looking for is called structured bindings and it will be available in C++17. They will allow you to create references to the elements of arrays, certain classes/structs and tuple like objects.

Since your looking for a pre C++17 solution really the best you can do is use std::tie to construct tuples that refer to what you want to assign like

int array[] = {1, 2, 3};
int a, b, c;
std::tie(a, b, c) = std::tie(array[0], array[1], array[2])

But that really doesn't save you much.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.