如何计算数组中相同的值
How to count same values in array c++
我试图计算网络上相同元素的数量,我在网上找到了这个简单的解决方案,但我正在调整它,所以我自己正确理解它。我试着数一下数组中有多少个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/
您链接到的示例使用称为ca
的std::array
。它接受元素的类型和数量,因此std::array<int, 6>
期望6个int
s,并且是一个固定长度的数组。
这有一个begin
和end
方法,并与stl中的算法很好地配合。
如果你有一个C风格的数组,你可以使用std::begin
和std::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;
}
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++数据文件、数组和计算赋值
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 有效地计算多维数组的累积和?
- 通过指针算法计算数组长度
- 计算数组重复次数的组合的有效算法,加起来达到给定的总和
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 当我使用需要计算数组单元格地址的模板时,奇怪的C++行为
- 传递数组和计算平均C++的问题
- 如何使用二维数组来计算和存储来自其他数组的值的频率
- C++使用 getArea() 并访问数组来计算圆的面积
- 从数组中计算平均值
- c++将文本中的数字读入整数数组,计算平均值
- c++从数组中计算正数/负数的数目
- 二维数组,计算并存储6个随机连接点
- c++数组,计算函数中的重复次数
- 从四个给定的无符号字符数组中计算平均数组
- 使用结构数组进行计算