Herpes Free Engineer
Herpes Free Engineer

Reputation: 2672

How to get size of nested std::initializer_lists?

std::initializer_list has a member function size that returns the number of elements in the initializer list.

Considering there is no [] operator for a std::initializer_list, and a user does not want to use for-loop to access the size of each sub-list:

How can a user get the size of an inner std::initializer_list from std::initializer_list<std::initializer_list>.

For example, from the following example, could you please tell me how a user can access the size of the first nested initializer_list, {1, 2, 3}?

#include <iostream>
#include <string>

int main()
{
  std::initializer_list<std::initializer_list<int>> a = { {1, 2, 3}, {2, 3, 4} };

  std::cout << a.size() << std::endl; // Provides = 2

  // Now I want to access the size of the first nested std::initializer_list:
  // std::cout << a[0].size() << std::endl; // Does not compile

  return 0;
}

Upvotes: 3

Views: 201

Answers (2)

songyuanyao
songyuanyao

Reputation: 172994

You can take advantage of std::initializer_list::begin,

Returns a pointer to the first element in the initializer list.

e.g.

std::cout << a.begin()->size() << std::endl;       // Provides = 3
std::cout << (a.begin() + 1)->size() << std::endl; // Provides = 3

Upvotes: 3

P.W
P.W

Reputation: 26800

You can do this:

for(const auto& ilist: a)
   std::cout << ilist.size() << std::endl; // Compiles

See Demo.

If required, you can assign the sizes to different variables within the for loop.

Upvotes: 1

Related Questions