c++ - 我应该如何在 C++ 中动态分配字符串指针?
问题描述
大家好! 我正在尝试为 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, 0, 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, 0, N-1, 0);
}
对此
void Radix::sortR(const std::vector<std::string>& a)
{
aux.resize(a.size()); //No problem!
sortR(a, 0, a.size()-1, 0);
}
您还必须更改其他版本sortR
以使用向量而不是指针。
您的代码无法工作,因为您无法将数组传递给 C++ 中的函数,因此此代码sizeof(a)/sizeof(std::string*)
不起作用,因为您的sortR
函数内部a
是一个指针。
作为一般规则,您不应new
在 C++ 程序中使用数组、指针。当然有很多例外,但您的首选应该是使用std::vector
。
推荐阅读
- python - 在 Python 中切片列表或字符串对象
- python - 一起使用flask(或elasticsearch)和nodejs webserver是否有意义?
- reactjs - 检查身份验证时,Reactjs 不应该自动重新加载吗?
- python - /adding-url-patterns-for-views 处的 ValueError
- java - 从 PDF 中删除嵌入文件时确保字节完整性
- jquery - 汉堡全屏菜单
- node.js - (猫鼬)如何在用户集合中搜索会话数组属性内的对象内的令牌
- python - 将矩阵(表示图像)存储在内存或磁盘中以使它们可用于 GUI 应用程序的明智方法是什么?
- c++ - 尝试制作树时在未对齐的地址中的成员访问
- python - 如何重新启动 Python 代码 - 重新启动数学测验