文章背景
笔者写作业时遇到的
题目如下
设有若干个长度不超过100的字符串(含空格和tab字符),设计各字符串的输入、输出及按大小(按ASCII值)排序的函数,
主函数main中让用户输入字符串个数,再调用输入、排序及输出函数,完成各字符串的处理。
【输入形式】
3 (用户输入字符串个数)
What’s this?
How old are you?
What? (用户输入的三个字符串)
【输出形式】
How old are you?
What’s this?
What?
阅读本文前置知识
- 了解vector的基本成员函数
- 了解cin的基本成员函数
正文
做这道题笔者的思路是,程序分为两大模块:
- 输入模块
- 冒泡排序模块
最初的代码如下(含有bug)
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int nums;
cin>>nums; //获取字符串个数
string input; //未对string初始化,默认初始化为空字符串,input==""
int nums_copy=nums;
vector<string> container;
while (nums_copy){
getline(cin,input);
container.push_back(input);
nums_copy--;
}
int rounds=0;
for (int i = 0; (i+1) <(nums-rounds) ; ++i) {
for (int j = 0; j+1 <nums-rounds ; ++j) {
if(container[j]>container[j+1]){
swap(container[j],container[j+1]);
}
}
rounds++;
}
for (int i = 0; i < nums; ++i) {
cout<<container[i]<<endl;
}
return 0;
}
经单步调试后发现,在vs2019环境下,会出现如下问题
- vector<string>容器允许入栈只含有空白符的字符串以及空字符串
"\n"
,""
cin>>nums
执行结束后,只有数字部分被cin读入nums,紧跟在数字部分后的,仍存在于输入流当中的\n
未被第七行代码读入,当getline(cin,input)
执行后,输入流缓存区当中的\n
将被读入,又因为getline
会舍弃换行符,因此getline
读入一个空字符串,之后入栈,container[0]==""
。导致最终只有nums-1
个字符串入栈
需对第十二行代码进行改动,正确代码如下
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int nums;
cin>>nums;
string input;
int nums_copy=nums;
vector<string> container;
while (nums_copy){
getline(cin.ignore(numeric_limits<streamsize>::max(),'\n'),input); //忽略缓存区的空字符串
container.push_back(input);
nums_copy--;
}
cout<<container[0];
int rounds=0;
for (int i = 0; (i+1) <(nums-rounds) ; ++i) {
for (int j = 0; j+1 <nums-rounds ; ++j) {
if(container[j]>container[j+1]){
swap(container[j],container[j+1]);
}
}
rounds++;
}
for (int i = 0; i < nums; ++i) {
cout<<container[i]<<endl;
}
return 0;
}
另一种可行,但是时间复杂度较高的改动方法为
令
nums++
,从而顺利入栈所有字符串(包括""
),再利用vector::erase()
删除第一个元素(""
)