如何计算数组中相同的值

How to count same values in array c++

本文关键字:数组 何计算 计算      更新时间:2023-10-16

我试图计算网络上相同元素的数量,我在网上找到了这个简单的解决方案,但我正在调整它,所以我自己正确理解它。我试着数一下数组中有多少个40。2.

#include <iostream>
#include <algorithm>
#include<array>
using namespace std;
int main(){
    int array[6] = {38,38,40,38,40,37};
    cout<<count(ca.begin(),ca.end(),40);
    return 0;
}

错误是ca未被识别,这里是我发现的帮助进行计数的代码。http://www.cplusplus.com/forum/general/154188/

您链接到的示例使用称为castd::array。它接受元素的类型和数量,因此std::array<int, 6>期望6个int s,并且是一个固定长度的数组。

这有一个beginend方法,并与stl中的算法很好地配合。

如果你有一个C风格的数组,你可以使用std::beginstd::end来实现同样的事情。

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';

当然不能识别ca,您忘记初始化它了:)

count函数需要接收要计数的范围的开始和结束。在您的示例中,数组从array开始,结束于array+5,但这是一个严格的比较,因此必须传递array+6

main变为:

int main(){
    int myArray[] = {38,38,40,38,40,37};
    cout << count(myArray, myArray+6 40);
    return 0;
}

数组不是类,也没有成员函数。而且你还有个错别字。我想你的意思是

int ca[6] = {38,38,40,38,40,37};
cout<<count(ca.begin(),ca.end(),40);

一样书写
cout << count( ca, ca + sizeof( ca ) / sizeof( *ca ), 40 );

或包含标题<iterator>

#include <iterator>

和写

cout << count( begin( ca ), end( ca), 40 );

另一方面,如果你要使用std::array类而不是你的array,那么你可以写

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

这里是一个示范程序

#include <iostream>
#include <array>
#include <algorithm>
#include <iterator>
int main() 
{
    int a1[6] = { 38, 38, 40, 38, 40, 37 };
    std::cout << std::count( std::begin( a1 ), std::end( a1 ), 40 ) << std::endl;
    std::array<int, 6> a2 = { 38, 38, 40, 38, 40, 37 };
    std::cout << std::count( a2.begin(), a2.end(), 40 ) << std::endl;
    return 0;
}