我正在实现一个简单的 merge
函数,但我卡住了,因为编译器给我无法解释的错误。这是我的 merge
函数:
void merge(void *a, int beg, int middle, int end, int (*cmp)(const void*, const void*
{
std::stack<void*> first;
std::stack<void*> second;
for(int i = beg; i < middle; i++) {
first.push(a+i);
}
for(int i = middle; i < end; i++) {
second.push(a+i);
}
for(int i = beg; i < end; i++) {
if(first.empty()) {
void *tmp = second.top();
second.pop();
a+i = tmp;
} else if(second.empty()) {
void *tmp = first.top();
first.pop();
a+i = tmp;
} else if(cmp(first.top(), second.top())) {
void *tmp = first.top();
first.pop();
a+i = tmp;
} else {
void *tmp = second.top();
second.pop();
a+i = tmp;
}
}
}
这里是错误:
sort.h: In function `void merge(void*, int, int, int, int (*)(const void*, const void*))':
sort.h:9: error: pointer of type `void *' used in arithmetic
sort.h:12: error: pointer of type `void *' used in arithmetic
sort.h:19: error: pointer of type `void *' used in arithmetic
sort.h:19: error: non-lvalue in assignment
sort.h:23: error: pointer of type `void *' used in arithmetic
sort.h:23: error: non-lvalue in assignment
sort.h:27: error: pointer of type `void *' used in arithmetic
sort.h:27: error: non-lvalue in assignment
sort.h:31: error: pointer of type `void *' used in arithmetic
sort.h:31: error: non-lvalue in assignment
谁能帮帮我? TIA。
最佳答案
void*
无法进行指针运算,因为 void
没有大小,而指针运算需要根据类型的大小计算内存地址。
如果您希望beg
、middle
和end
来表示字节偏移,您应该使用 char
指针代替(一个 char
是一个字节)。
如果你想写一个适用于任何类型的泛型函数,不要使用void
指针,而是使用模板:
template <typename t>
void merge(T *a, int beg, int middle, int end, int (*cmp)(const T*, const T*))
{
// ...
}
关于c++ - 如何使用无效*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11247584/