C++ 我想从特定的c++;排列
我创建了一个函数来计算数组中的重复项。C++ 我想从特定的c++;排列,c++,arrays,C++,Arrays,我创建了一个函数来计算数组中的重复项。 一切都很好。但我只想输出唯一的项,这是我的问题 我的功能: void RepeatedCounter(int n){ int i, j, temp, count= 0; int *Numbers = new int[n]; for(i=0;i<n;i++){ cout << "Enter the number (" << i+1 << "): "; cin
一切都很好。但我只想输出唯一的项,这是我的问题 我的功能:
void RepeatedCounter(int n){
int i, j, temp, count= 0;
int *Numbers = new int[n];
for(i=0;i<n;i++){
cout << "Enter the number (" << i+1 << "): ";
cin >> *(Numbers+i);
}
cout << "---------------------\n";
for(i=0;i<n;i++){
temp = *(Numbers+i);
for(j=0;j<n;j++){
if(temp == *(Numbers+j)){
++count;
}
}
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
count= 0;
}
delete []Numbers;
}
错误结果(电流输出)
int Num_Of_Digits= 0;
cout << "How many numbers: ";
cin >> Num_Of_Digits;
RepeatedCounter(Num_Of_Digits);
Inputs
1
5
3
5
1
1= 2
5= 2
3= 1
5= 2
1= 2
1= 2
5= 2
3= 1
我想要什么
int Num_Of_Digits= 0;
cout << "How many numbers: ";
cin >> Num_Of_Digits;
RepeatedCounter(Num_Of_Digits);
Inputs
1
5
3
5
1
1= 2
5= 2
3= 1
5= 2
1= 2
1= 2
5= 2
3= 1
这是为你做的
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
int repeated_counter(int n){
std::vector<int> vec;
std::vector<int> uniques;
int t;
for(int i=0; i!=n; ++i)
{
std::cin >> t;
vec.push_back(t);
}
std::sort(vec.begin(), vec.end());
std::unique_copy(vec.begin(), vec.end(),
std::back_inserter(uniques));
for(std::vector<int>::iterator it=uniques.begin();
it!=uniques.end();
++it)
{
std::cout << *it << "="
<< std::count(vec.begin(), vec.end(), *it) << "\n";
}
return 0;
}
#包括
#包括
问题在于,您只是在对照列表中的下一个数字进行检查
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
if(*(数字+i+1)!=temp)
cout第一步:将用户数据读入一个合适的动态容器,如向量
:
std::vector<int> v;
v.reserve(100);
while (true)
{
int n;
std::cout << "Enter the number: ";
if (!(std::cin >> n)) { break; }
v.push_back(n);
}
现在输出计数:
for (auto const & p : histogram)
{
std::cout << "The number " << p->first
<< " appears " << p->second << " times.\n";
}
for(自动常量&p:直方图)
{
std::cout试试这个
for(i=0;i<n;i++){
count= 0;
temp = *(Numbers+i);
bool found = false;
for(j=0;j<n;j++){
if(temp == *(Numbers+j)){
++count;
}
}
for(j=i+1;j<n;j++) {
if(temp == *(Numbers+j)){
found = true;
}
}
if(found) continue;
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
}
用于(i=0;iA频率表可能就是你要找的。@桑德·德戴克:谢谢,但我还是c++初学者如果你是初学者,那么你应该学会用正确的方法而不是愚蠢的方法。看看@Kerrek SB的答案,了解如何使用频率表的示例。你确定unique\u copy
不需要排序器吗ange?@111111:谢谢,但我不想用vector,我想要其他的way@LionKing为什么?它在各个方面都更糟,在这个用例中它绝对没有优势。@ 111111:对不起,但是我还是C++初学者,我还是不懂向量。good@111111unique_copy不需要一个排序范围来定义它的行为,但它是打开的ly消除连续的重复。如果存在不连续的重复,则这些重复将被复制到输出范围。排序是保证所有重复都是连续的典型方法。不幸的是,仍然不起作用,但这次发生了另一个问题。代码现在工作正常,这就是我所做的蚂蚁(你应得的)