应该出现我有以下字符串集串contarting“<cr>”最后在排序
'aa'
'hello'
'start'
'<1-10>'
'<cr>'
当我的qsort使用从C中的排序库,我得到下面的输出
<1-10>
<cr>
aa
hello
start
但我想要以下输出
<1-10>
aa
hello
start
<cr>
感谢您的帮助。
应该出现我有以下字符串集串contarting“<cr>”最后在排序
'aa'
'hello'
'start'
'<1-10>'
'<cr>'
当我的qsort使用从C中的排序库,我得到下面的输出
<1-10>
<cr>
aa
hello
start
但我想要以下输出
<1-10>
aa
hello
start
<cr>
感谢您的帮助。
<cr>
的字符串移动到不同的容器中。<cr>
而且,而是采用单独的容器,你可以在年底移动包含<cr>
字符串列表(std::partition
),并在两个子阵列上应用qsort
。
bool partitioner(string str) {
return str.find("<cr>") == string::npos;
}
现在:
vector<string> v {"hello", "world", "<cr>", "<cr>string"};
auto bound = partition(v.begin(), v.end(), partitioner);
sort(v.begin(), bound);
sort(bound, v.end());
我不知道您的实际设置,因为vector
是一个C++类,而你的国家,你要使用C. 不管怎样,也许以下为std :: vector编写的代码与std :: sort结合使用,显示了基本原理,您可以在其中引入用于排序的自定义比较函数。请注意,qsort
也允许自定义比较函数,但语法会有所不同。
自定义比较函数的工作原理如下:如果两个字符串都以<
开头,则比较它们的余数。如果其中一个以<
开头,那么这个总是排在另一个之下。否则,他们只是比较。我用char*
- 数据类型跟上的C一番风味为你:-):
int main() {
std::vector<const char*> s = {
"aa",
"start",
"hello",
"<d-10>",
"<cr>"
};
// sort using a custom function object
struct {
bool operator()(const char*a, const char*b)
{
if (*a == '<') {
if (*b == '<') {
return strcmp(a+1,b+1) < 0;
}
else {
return false;
}
}
else if (*b == '<') {
if (*a == '<') {
return strcmp(a+1,b+1) < 0;
}
else {
return true;
}
}
else
return strcmp(a,b) < 0;
}
} customLess;
std::sort(s.begin(), s.end(), customLess);
for (auto a : s) {
std::cout << a << std::endl;
}
return 0;
}
输出:
aa
hello
start
<cr>
<d-10>
请出示你的代码。我们不介意读者,也不会在没有看到它的情况下告诉你它有什么问题。请仅使用相关的语言标签 - C和C++是不同的语言。 – kaylum
C或C++?你想要使用哪个数据结构作为字符串list/array/raw pointer array/vector/...? –
C,我正在使用vector – deathstroke05