开发者

count specific number of elements

开发者 https://www.devze.com 2023-03-04 23:58 出处:网络
For example, if I have an array of 5 inputted elements, how would I count how many times a specific value was entered if that value has already been established in a variable.

For example, if I have an array of 5 inputted elements, how would I count how many times a specific value was entered if that value has already been established in a variable.

INPUT:
4
4
4
1
2

If click is defin开发者_如何学运维ed as 4 then how would I count how many times click is used in the array? Hopefully that makes sense. Thanks


As you've tagged your question as C++, here is a proper C++ answer, using STL.

int num = std::count(&array[0], &array[5], click);

See http://en.cppreference.com/w/cpp/algorithm/count


This is how you would do it with C style arrays.

int i;
int count = 0;
for(i = 0; i < ARRAYSIZE; ++i)
{
    if(array[i] == click)
        ++count;
}

ARRAYSIZE is the size of your statically allocated array, array your array variable and click the value you are looking for. In count the count of the variable is saved.


You could use count.

Something like this (sorry I'm out of practice with C++):

#include <algorithm>

void someFunction() {
    int input[5];
    // initialize input with some values
    int num = std::count(&input[0], &input[5], 4);
}


If it isn't sorted, then linear search is your only choice.

0

精彩评论

暂无评论...
验证码 换一张
取 消