我需要编写一个程序来输入由空格分隔的整数,例如:
4 4 5 8 8 9
程序然后获取这些数字并计算每个数字出现的次数,因此上述输入的输出将是:
The number 4 has 2 occurrence(s)
The number 5 has 1 occurrence(s)
The number 8 has 2 occurrence(s)
The number 9 has 1 occurrence(s)
我几乎已经弄清楚了,当我为数字没有用空格分隔的输入时它工作得很好(假设它们是 1 位整数,而不是我为最终版本所做的假设)但是一旦输入的数字之间有空格,它就不再有效。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
vector<int> parseString(string &s);
void parseVector(vector<int> &v);
int checkRepeats(vector<int> &v, int n);
void printVector(vector<int> &v);
int main()
{
vector<int> parsed;
vector<int> numbers;
string input;
bool keepGoing = true;
int nRepeats; // stores the number of times a number occurs, will constantly be overwritten
cout << "Enter some numbers: ";
while(true)
{
cin >> input;
if(input == "stop" || input == "Stop")
{
break;
}
parsed = parseString(input); // parse input string to vector of ints
parseVector(parsed); // send vector of ints to be checked for repeats
//printVector(parsed);
//cout << "\n";
}
}
void printVector(vector<int>&v) // not called right now, used for testing
{
for(int i = 0; i < v.size(); i++)
{
cout << v.at(i) << " ";
}
}
void parseVector(vector<int> &v)
{
int x = 0;
int j = 0;
int nRepeats = 0;
int size = v.size();
for(int i = 0; i < size; i++)
{
x = v.at(i); // x equals the next element in vector 'v'
nRepeats = checkRepeats(v, x); // count the number of times number 'x' occurs in vector 'v'
//i += nRepeats - 1;
cout << "The number: " << x << " has: " << nRepeats << " occurrence(s)\n";
}
}
int checkRepeats(vector<int> &v, int n) // counts the number of times a number is found in a given vector
{
int nTimes = 0;
int size = v.size();
for(int i = 0; i < size; i++)
{
if(v.at(i) == n) // match found, increment counter
{
nTimes++;
}
}
return nTimes;
}
vector<int> parseString(string &s)
{
vector<int> v;
int strLen = s.size();
int x;
for(int i = 0; i < strLen; i += 2) // increment by 2 to cut out white space from between the numbers
{
x = s.at(i);
x -= 48; // subtract 48 from x, converts from ascii to int value
v.push_back(x);
}
return v;
}
如果你转到该代码的第 88 行,并将循环计数器的增量从 i += 2
更改为 i++
,它将完美地用于没有输入的情况空格,例如 445889
而不是 4 4 5 8 8 9
有人知道我可以尝试解决这个问题吗?
最佳答案
你可以尝试使用 map ( super 天真的版本:)
#include <map>
#include <iostream>
int main()
{
int i;
std::map<int, int> ints;
while (std::cin >> i)
++ints[i];
for (auto const& num : ints)
std::cout <<
"The number " <<
num.first <<
" has " <<
num.second <<
" occurrence(s)\n";
}
关于c++ - 无法通过 C++ vector 进行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751835/