优化代码#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <iterator> using namespace std; int main() { string from, to; cin >> from >> to; ifstream is(from.c_str()); istream_iterator<string> ii(is); istream_iterator<string> eos; vector<string> b(ii, eos); sort(b.begin(), b.end()); ofstream os(to.c_str()); ostream_iterator<string> oo(os, "\n"); unique_copy(b.begin(), b.end(), oo); return (!is.eof() || !os); }
时间: 2024-02-25 13:53:42 浏览: 20
这段代码已经比较简洁高效,但还可以进行一些优化,例如:
1. 使用 `auto` 关键字
可以使用 `auto` 关键字来自动推断变量类型,使代码更简洁。
示例:
```
auto ii = istream_iterator<string>(is);
auto eos = istream_iterator<string>();
auto b = vector<string>(ii, eos);
```
2. 使用 `string` 构造函数
可以使用 `string` 构造函数来简化字符串的创建和转换。
示例:
```
ifstream is(from);
vector<string> b(istream_iterator<string>(is), istream_iterator<string>());
```
```
ofstream os(to);
copy(b.begin(), b.end(), ostream_iterator<string>(os, "\n"));
```
3. 使用 lambda 表达式
可以使用 lambda 表达式来简化排序和去重操作。
示例:
```
sort(b.begin(), b.end(), [](const string& a, const string& b){ return a < b; });
unique_copy(b.begin(), b.end(), oo, [](const string& a, const string& b){ return a == b; });
```
优化后的代码如下:
```
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
string from, to;
cin >> from >> to;
ifstream is(from);
vector<string> b(istream_iterator<string>(is), istream_iterator<string>());
ofstream os(to);
ostream_iterator<string> oo(os, "\n");
sort(b.begin(), b.end(), [](const string& a, const string& b){ return a < b; });
unique_copy(b.begin(), b.end(), oo, [](const string& a, const string& b){ return a == b; });
return (!is.eof() || !os);
}
```