问题描述
大家好! 我正在尝试为C ++中的字符串指针动态分配空间,但是我遇到了很多麻烦。
我编写的代码部分是(关于RadixSort-MSD):
class Radix
{
private:
int R = 256;
static const int M = 15;
std::string aux[];
int charat(std::string s,int d);
void sortR(std::string a[]);
public:
void sortR(std::string a[],int left,int right,int d);
};
这是有问题的部分:
void Radix::sortR(std::string a[])
{
int N = sizeof(a)/sizeof(std::string*);
aux = new std::string[N]; //Here is the problem!
sortR(a,N-1,0);
}
下面是我尝试编译项目时出现的错误,它与变量“ aux”有关,它是一个字符串指针。
|15|error: incompatible types in assignment of 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' to 'std::__cxx11::string [0] {aka std::__cxx11::basic_string<char> [0]}'|
我完全是菜鸟巴西C ++学生。所以我不明白错误消息在说什么。
你能帮我吗?
解决方法
使用std::vector
。更改
std::string aux[];
对此
std::vector<std::string> aux;
还有这个
void Radix::sortR(std::string a[])
{
int N = sizeof(a)/sizeof(std::string*);
aux = new std::string[N]; //Here is the problem!
sortR(a,N-1,0);
}
对此
void Radix::sortR(const std::vector<std::string>& a)
{
aux.resize(a.size()); //No problem!
sortR(a,a.size()-1,0);
}
您还必须更改sortR
的其他版本,以使用向量代替指针。
您的代码无法工作,因为您无法将数组传递给C ++中的函数,因此此代码sizeof(a)/sizeof(std::string*)
不起作用,因为您的sortR
函数a
内部是一个指针。 / p>
通常,您不应在C ++程序中使用数组,指针或new
。当然,有很多例外,但您的首选应该是使用std::vector
。