【发布时间】:2019-09-25 13:20:47
【问题描述】:
我想对包含整数的文件进行排序,但只想逐行排序。我试过了,但我确定我在下面做的不是到位。
void sort_file_in_place(const char* filename) {
fstream sort_file;
sort_file.open(filename, ios::out | ios::in);
vector <vector <int> > input_vect;
string line;
std::string delimiter = " ";
int vect_index = 0;
while (getline(cin, line)) {
//store into vector of vectors
//tokenise string
size_t pos = 0;
int value = 0;
int count = 0;
while ((pos = line.find(delimiter)) != std::string::npos) {
string token = line.substr(0, pos);
line.erase(0, pos + delimiter.length());
value = std::atoi(token.c_str());
count++;
}
input_vect.resize(vect_index++, vector<int>(count));
}
//sort vector of vectors
for (int i = 0; i < input_vect.size(); i++) {
sort(input_vect[i].begin(), input_vect[i].end(), std::less<int>());
//print the sorted vectors and alos verify the content
for (auto v : input_vect[i]) cout << v << " ";
}
//write back into the file
//Todo
}
上面的代码不完整,但我希望你能得到我想问的。
请提出更好的解决方案。
我还想使用不同的线程对这些行进行排序,例如:
如果文件内容是:
13 38 13 100 4 234 85 34 0 100 88
1 4 5 3 8 9 1 10
111 10 112 3 4 098 194
5 4 8 3 9 13 24 78 09 99
我想创建四个线程来对每一行进行就地排序。
【问题讨论】:
-
请只问一个问题。现在有多个:“如何在文件中逐行排序整数?”和“我如何在另一个线程上运行算法?”,(还有争议的第三个:“我如何将算法的工作分配给四个线程?”)
-
我应该编辑这个问题吗?
-
管理线程有开销。截至 2019 年,我预计线程所需的原始值 (
integers) 的数量将有助于达到数千个。 -
您正在使用就地工作的 std::sort 。您的代码看起来不错,您有什么改进意见?
-
@Amaresh 你不能避免缓冲区,你不能'直接在文本文件中'排序。
标签: c++ algorithm file sorting concurrency