排序基于从文件密钥 [英] sorting based on key from a file
问题描述
我需要排序的东西从类似于以下的文件中读取:
I need to sort stuff read from a file similar to the following:
Key: 2 rec:1 2 3 4 5 6 ...
Key: 3 rec:7 8 9 10 11 ...
Key: 1 rec:A B C D E F ...
变为
Key: 1 rec:A B C D E F ...
Key: 2 rec:1 2 3 4 5 6 ...
Key: 3 rec:7 8 9 10 11 ...
如果我们有一些在关键的REC(录音)排序,其将保持不变!作为排序基于关键。我想使用的qsort(c)中定义的排序。我有一个主意,用的strtok打破从文件中读入管理的阵列的每一行,但我不是,如果是找到钥匙号码,以便他们与C库的qsort进行排序的最好方式。
and if we have something unsorted in rec (record ) of a key, it will remain unchanged! as sorting is based on the key. I want to use qsort() defined in C for sorting. I have an idea to use strtok for breaking each line read from file into manageable arrays but I am not if it's the best way to find the key number so as to sort them with qsort from C library.
P.S:输入文件的每一行包括像钥匙一键:1 REC:A B C D E F ...
同时,我们也不会在关键中的记录进行排序。
P.S.: Each line of the input file includes one key like Key: 1 rec:A B C D E F ... Also we won't sort records within a key.
推荐答案
要做到这在C,使用的 sscanf的,你可以得到一种正则表达式来提取所需要的整数:
To do this in c, make use of sscanf and you can get a sort of regex to extract the integer needed:
int comp(const void *str1, const void *str2) {
char *a = *(char **)str1, *b = *(char **)str2;
int key1, key2;
sscanf(a, "%*s%d", &key1);
sscanf(b, "%*s%d", &key2);
return key1-key2;
}
//Call the function qsort like so
qsort(/*char **/lines, /*int*/numElements, /*unsigned*/ sizeof (char*), comp);
不知道如何使用正则表达式库在C ++中,但的sscanf
仍然有效。在C ++ 11全部工作的例子:
Don't know how to use the regex library in c++, but sscanf
still works. Full working example in c++11:
#include <iostream>
#include <cstdio>
#include <deque>
#include <string>
#include <algorithm>
int main() {
//Using fstream, read in each line of the file into a string using getline(...)
std::deque<std::string> lines = {
"Key: 2 rec:1 2 3 4 5 6",
"Key: 3 rec:7 8 9 10 11",
"Key: 1 rec:A B C D E F",
"Key: 4 rec:1 2 3 4 5 6"
}; //Store each in a deque object
//using std::sort
std::sort(lines.begin(), lines.end(), []( const std::string &str1, const std::string &str2 ) {
int key1, key2;
sscanf(str1.c_str(), "%*s%d", &key1);
sscanf(str2.c_str(), "%*s%d", &key2);
return (key1 < key2);
});
for (auto sortedkeys: lines)
std::cout << sortedkeys << "\n";
return 0;
}
这篇关于排序基于从文件密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!