Masnad Nehith Masnad Nehith - 11 months ago 85
C++ Question

How to count same values in array c++

I am trying to count the number of same elements on the net, I found this easy solution on the net but I am adjusting it so I understand it properly by myself.
I am trying to count how many number of 40 are there in the array. Which is 2.

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
int array[6] = {38,38,40,38,40,37};
return 0;

The error is that ca is not recognised, and here is the codes that I found to help work this counting.

Answer Source

The example you have linked to is using a std::array called ca. It takes a type and number of elements, so std::array<int, 6> expects 6 ints and is a fixed length array.

This has a begin and end method and plays nicely with the algorithms in the stl.

If you have a C style array instead, you can use std::begin and std::end to achieve the same thing.

array<int, 6> ca{ 38,38,40,38,40,37 };
cout << count(ca.begin(), ca.end(), 40) << '\n';

int c_style_array[] = { 38,38,40,38,40,37 };
cout << count(std::begin(c_style_array), std::end(c_style_array), 40) << '\n';