自己的学习笔记,如有错误,还请指正,谢谢。
初代版 :
输入字符串直到“**”结束,对字符数组进行排序,再强行用了向量的函数。
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string arr[100];
int i = 0;
cout << "Please enter words until '**':"<< endl;
do{
cin >> arr[i];
i++;
} while (arr[i-1] != "**");
cout << "You have enter "<< i - 1 << " words" << endl;
cout << "Before sort:" << endl;
for (int j = 0; j < i-1 ; j++)
{
cout << arr[j] << " ";
}
cout << endl;
sort(arr, arr + i-1);
vector<string> v;
for (int j = 0; j < i-1; j++)
{
v.push_back(arr[j]);
}
cout << "After sort:" << endl;
for (int j = 0; j < v.size(); j++)
cout << v[j] << ' ';
cout << endl;
return 0;
}
改进版:
挨个挨个的读入单词,然后把每个单词放到容器中,再排序。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> vectStrings;
string word;
char ch;
do {
cout << "Введите слово:";
cin >> word;//读取到空格结束
//getline(cin, word); 整个一行读取直到分隔符
vectStrings.push_back(word);
cout << "Продолжать ('y' или 'n'):";
cin >> ch;
} while (ch == 'y');
sort(vectStrings.begin(), vectStrings.end());
for (int k = 0; k < vectStrings.size(); k++)
cout << vectStrings[k] << endl;
return 0;
}
高阶版:
输入一句英文含有空格,把句子中的单词提取出来,然后使用向量容器把它装进去,进行排序。
用到了getline函数、for (auto x : str)函数、v.push_back( )函数、sort(v.begin(), v.end());
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/*
void removeDupWord(string str)
{
string word = "";
for (auto x : str)
{
if (x == ' ')
{
cout << word << endl;
word = "";
}
else {
word = word + x;
}
}
cout << word << endl;
}
*/
int main()
{
vector<string> vectStrings;
string str;
getline(cin, str);
string word = "";
for (auto x : str)
{
if (x == ' ')
{
cout << word << endl;
vectStrings.push_back(word);
word = "";
}
else {
word = word + x;
}
}
cout << word << endl;
vectStrings.push_back(word);
cout<<endl;
sort(vectStrings.begin(), vectStrings.end());
for (int k = 0; k < vectStrings.size(); k++)
cout << vectStrings[k] << endl;
return 0;
}