使用排序函数 c++ 对字符数组进行排序



我试图将用户输入限制为字母表,然后按升序对所有字符进行排序。

构建消息 错误:调用"std::__cxx11::basic_string::basic_string(char&("没有匹配函数

这是我的标题

#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
#include <regex>

我应该将字符转换为字符串,然后为我的以下代码转换回字符吗?

string Sortstr (str[mlength]);
sort(Sortstr.begin(), Sortstr.end());

收到此 2 行错误。

int mlength = 100;
int main() {
char str[mlength];
int length;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'n');
regex pass1("^[a-zA-Z]+");
while(!regex_match(str,pass1)) {
cout<<"Error"<<endl;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'n');
}
string Sortstr (str);
sort(str, str + strlen(str));
}

为什么不直接str排序?

sort(str, str + strlen(str));

没有理由不能直接对数组进行排序。只需将指向数组的第一个和一次性元素的指针传递给sort。在这种情况下,添加strlen会得到一个指向数组有效端的指针。

在这一行中

string Sortstr (str[mlength]);

您正在对 char 数组使用索引运算符,该数组为您提供一个 char。因此,您将一个字符传递给字符串构造函数。此构造函数不存在,因此出现错误。即使它存在,您也不想传递单个字符,而是传递整个字符数组。

你想要的是这个:

string Sortstr (str);

最新更新