Ian Chiang
Ian Chiang

Reputation: 69

Is there a function for accessing the amount of elements that have a value in an std::array?

In C++, assume I have an std::array<std::optional<std::int>, 5> array. Let's say I set the first 3 elements to be of a certain value. Is there a function that when passed array returns 3 (i.e. Returns the number of elements that has an assigned value)? Or is there anyway to improve the std::array so that it supports this functionality? I appreciate your help.

P.S. Guaranteed: The array's elements are always consecutive. For instance,

std::array<std::optional<std::int>, 5> arr;
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
cout << func(arr) << endl; // Returns 4 in this case

Edit 1. I already knew about std::count, but I do not know how to check if an element is defined. Also, the array could be of any type.

Edit 2. What if I used std::optional? How could I do that, then?

Upvotes: 0

Views: 82

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

I already knew about std::count, but I do not know how to check if an element is defined.

You can use std::count_if() for this, eg

std::array<std::optional<int>, 5> arr;
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
auto cnt = std::count_if(arr.begin(), arr.end(),
    [](const auto &elem){ return elem.has_value(); }
);
std::cout << cnt << std::endl; // Returns 4 in this case

Upvotes: 2

Related Questions