写一个文本,然后编写一个程序,打开文本然后将每一个字读取到一个vector对象中。遍历vector,将内容显示到cout。然后利用泛型算法sort(),对文字进行排序。
#include <algorithm>
sort(container.begin(), contaner.end())
再将排序后的结果输出入另一个文件。
#include <iostream>
#include <fstream> //读取文件的头文件
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ifstream infile("new1.txt"); //验证是否可以打开文件
if (! infile) //当不能打开时满足条件
{
cerr << "please check the file\n"; //cerr和cout一样
} //但对输出结果无缓存(bufferred)
ofstream outfile("new2.txt"); //立即显示与终端
if(! outfile)
{
cerr << "please check the file\n";
}
string word;
vector<string> msg;
while(infile >> word) //将文本中的内容读取到字符串word中,知道录取到最后一个字符,返回值为0
{
msg.push_back(word); //vector.push_back() 相当于将字符串的内容分配给vector中。类比数组
}
unsigned int i; //为什么是unsigned? 因为i需要与vector.size()作比较,后者为unsigned类型
cout << "unsorted msg: \n";
for(i = 0; i < msg.size(); i++) //遍历vector msg
{
cout << msg[i] << ' ';
}
cout << endl;
sort(msg.begin(), msg.end( )); //进行sort()操作
/*outfile << "sorted msg: \n"; //写入outfile
for(i = 0; i < msg.size(); i++) //遍历sort()后的vector msg,再将其写进outfile
{
outfile << msg[i] << ' ';
}
outfile << endl;*/
cout << "sorted msg: \n"; //这里选择直接输出看结果(与写如outfile中的内容相同)
for(i = 0; i < msg.size(); i++) //遍历sort()后的vector msg
{
cout << msg[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}