在 C++ 中重复数组中的整数元素的次数
how many times repeat integer elements in array in C++
#include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL,"Turkish");
int dizi[10]={9,30,3,6,9,20,3,6,10,9};
int counter, j;
for(int i=0; i<10; i++){
counter=1;
for(int j=i+1; j<10; j++){
if(dizi[i]==dizi[j+1]){
counter++;
}
}
cout<<dizi[i]<<"t:"<<counter<<endl;
}
}
/*
//THE RESULT
9 :3
30 :1
3 :2
6 :2
9 :2 //WRONG I don't want this line to appear
20 :1
3 :1 //WRONG I don't want this line to appear
6 :1 //WRONG I don't want this line to appear
10 :1
9 :1 //WRONG I don't want this line to appear
*/
我更喜欢使用STL来解决此类问题。遍历数组,以counts
计算出现次数,并将顺序存储在order
中。
#include <iostream>
#include <unordered_map>
#include <vector>
int main()
{
int dizi[] = { 9, 30, 3, 6, 9, 20, 3, 6, 10, 9 };
std::unordered_map<int, std::size_t> counts;
std::vector<int> order;
for (const auto &el : dizi) {
if (counts.find(el) == counts.end()) order.push_back(el);
++counts[el];
}
for (const auto &el : order) {
std::cout << el << "t:" << counts[el] << 'n';
}
return 0;
}
输出:
9 :3
30 :1
3 :2
6 :2
20 :1
10 :1
看来你的意思是以下几点
#include <iostream>
int main()
{
int dizi[] = { 9, 30, 3, 6, 9, 20, 3, 6, 10, 9 };
const size_t N = sizeof( dizi ) / sizeof( *dizi );
for ( size_t i = 0; i < N; i++ )
{
size_t j = 0;
while ( j != i && dizi[j] != dizi[i] ) ++j;
if ( j == i )
{
size_t counter = 1;
while ( ++j != N )
{
if ( dizi[j] == dizi[i] ) ++counter;
}
std::cout << dizi[i] << ":t" << counter << 'n';
}
}
return 0;
}
程序输出为
9: 3
30: 1
3: 2
6: 2
20: 1
10: 1
也就是说,您需要检查当前值是否已被抵消。
相关文章:
- C++:如何循环通过向量中的整数元素
- C++ 如何比较n个排序的整数向量以找到互元素?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 在 C++ 中重复数组中的整数元素的次数
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- C++向数组添加元素并调整数组大小
- AVX2 整数乘以有符号 8 位元素,产生有符号 16 位结果?
- 查找多个向量之间的公共元素(无整数元素)
- 整数指针数组的元素是否可以指向整数数组?
- " ans += (a[i] - ans * r > 0); "是什么意思,其中 ans,r 是整数,a[i] 是数组元素?
- 调整数组大小并添加元素 C++
- 将数字的字符串数组转换为整数数组时,元素将变为 0
- 在非负整数的未排序数组中查找第 k 个最小元素
- 给定一个包含 n 个整数和一个整数 x 的未排序数组 A,重新排列 A 中的元素
- 打印整数指针元素时的结果不同
- 为什么 Vector<double> 接受整数元素initializer_list?
- 如何有效地用不同的整数元素替换字符字符串的元素
- 对向量的整数元素进行排序
- std::vector中非整数元素的和
- 为什么我得到这种输出,因为我知道数组中未初始化的整数元素的默认值是0