C++ 对指向结构的常量指针数组进行排序
C++ Sorting array of const pointers to structs
我有排序功能:
void countingSort(TPhone * const * array, int count) {
// some code
// making copy od array
TPhone * const * arrayCopy = new TPhone * [count];
for(int i = 0; i < count; i++) {
arrayCopy[i] = array[i];
}
for(int i = 0; i < count; i++) {
int index = // some function to determine where to place array[i]
array[index] = arrayCopy[i];
}
}
我省略了有关排序算法的详细信息,因为问题出在其他地方。问题是,arrayCopy
的声明有问题。
在线上
arrayCopy[i] = array[i]
...
array[index] = arrayCopy[i];
我收到此错误消息
error: assignment of read-only location ‘*(arrayCopy + ((sizetype)(((long unsigned int)i) * 8ul)))’
error: assignment of read-only location ‘*(array + ((sizetype)(((long unsigned int)index) * 8ul)))’
声明中的const
用法一定有问题,但我不知道如何解决......
从右到左读取常量和指针声明:
TPhone * const * arrayCopy
^ ^ ^ ^ ^
| | | | ---- arrayCopy is a
| | | ------------ pointer to
| | ------------------- const
| -------------------------- pointer to
--------------------------------- TPhone
因此,arrayCopy 实际上是一个常量指针数组(数组也是如此)。 常量指针不能移动(即你不能改变它们指向的位置)。 因此,您无法覆盖它们,因此无法对它们进行排序。
如果你想要一个指向常量 TPhone 的指针数组(即,你不能改变 TPhone 的字段,但你可以移动指针),那么你应该移动 const:
pointer to constant TPhone:
TPhone const * // right-to-left
array of pointer to constant TPhone:
TPhone const * [] // right-to-left
but since arrays can't easily be passed to functions, you can use a pointer:
TPhone const * * // right-to-left
然后,您可以更改指针(只是内存地址),但不能更改实际的 TPhone 对象。
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”