C++ 尝试计数不同的字符串,出了什么问题
这种方法有什么错C++ 尝试计数不同的字符串,出了什么问题,c++,C++,这种方法有什么错 #include<algorithm> #include<iomanip> #include<ios> #include<iostream> #include<string> #include<vector> using std::cin;using std::cout; using std::endl; using std::setprecision; using std::string; using
#include<algorithm>
#include<iomanip>
#include<ios>
#include<iostream>
#include<string>
#include<vector>
using std::cin;using std::cout;
using std::endl;
using std::setprecision;
using std::string;
using std::streamsize;
using std::sort;
using std::vector;
int main(){
string zz;
typedef vector<string> vs;
vs input,distinct;vector<int> count;
cout<<"Enter the words";
while(cin>>zz){
input.push_back(zz);
}
if(input.size()==0){
cout<<"Enter atleast a single word";
return 1;
}
int i=0,j=0;
sort(input.begin(),input.end());
while(i!=input.size()){
int count2=0;
for(j=i;j<input.size();j++)
{
if(input[j]==input[j+1])
{
count2++;
}else{
break;
}
}
distinct.push_back(input[i]);
count.push_back(count2);
i+=count2;continue;
i++;
}
for(i=0;i<distinct.size();i++)
{
cout<<distinct[i]<<"\t time"<<count[i]<<"\n";
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
使用std::cin;使用std::cout;
使用std::endl;
使用std::setprecision;
使用std::string;
使用std::streamsize;
使用std::sort;
使用std::vector;
int main(){
串zz;
typedef向量vs;
vs输入,不同;向量计数;
库茨){
输入。推回(zz);
}
if(input.size()==0){
cout问题不在于您的读取循环。它会卡在一个无限循环中
while(i!=input.size()){
仔细考虑您的最终条件,以及更改的行i
:
i+=count2;continue;
i++;
i++
是否会被执行?i
是否会完全相等input.size()
?是否有重复的单词?是否没有
好的,考虑过了吗?我用这个替换了这个循环。注释应该解释:
while(i < input.size())
{
// Store current string
distinct.push_back(input[i]);
// Skip same strings
int j = i;
while ( j < input.size() // Don't go too far
&& input[i] == input[j] ) // And only while duplicates
++j;
// Store a count of how many we skipped
count.push_back(j-i);
// Move to the next *non-identical* string
i=j;
}
while(i
当然,有很多更好的方法可以使用标准库算法来实现这一点,但我认为这是一个简单的教育练习
还请注意,我写的这一轮很重要!另一轮,你试图将最后一个字符串与末尾的某个字符串进行比较。当EOF?include?include?include?include?这些是include。我是从mobile询问的,所以上面没有code测试文件结尾的条件是从while(cin>>zz)开始在你的PC程序上测试它。(你这样做了。)输入。观察到的行为。预期的行为。我发誓,如果我看到字符串向量的另一个typedef
,我会大发雷霆。:-d如果我不想对给定的数据排序并执行给定的任务,该怎么办