0

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?

21
  • 1
    Are you looking for std::count? Commented Jun 3, 2021 at 1:59
  • en.cppreference.com/w/cpp/algorithm/count Commented Jun 3, 2021 at 1:59
  • Is your array sorted? Commented Jun 3, 2021 at 2:00
  • @prehistoricpenguin No. Any array could work. Commented Jun 3, 2021 at 2:01
  • 1
    Use std::count_if Commented Jun 3, 2021 at 2:28

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

The elem::has_value() function is interesting. I will use that in future applications. Thank you very much! +1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.