0

How do I access a value from this initializer declared using auto keyword?

auto arr = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
auto a = arr[0];

Give the following compile-error on VS:

binary '[' : 'std::initializer_list' does not define this operator or a conversion to a type acceptable to the predefined operator

2 Answers 2

3

Take a look at the interface of std::initializer_list:

auto arr = { "one", "two", "three", "four", "five", "six",
              "seven", "eight", "nine" };
auto a = *arr.begin();

(or, to be more practical, initialize a container or an array with your braced-init-list)

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

1 Comment

That's it. I'm not much used to C++'s way (since I do it much in "C's way") like begin().
2

You can use iterators to traverse the initializer list. Function begin() returns a pointer to the first element in the initializer list.

int main() {

    auto arr = { "one", "two", "three", "four", "five", "six",
              "seven", "eight", "nine" };
    auto a = *arr.begin();
    auto b = *( arr.begin() + 1);

    cout << a << "," << b; // prints: one,two

    return 0;
}

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.