【发布时间】:2021-03-30 08:24:47
【问题描述】:
我正在尝试使用另一个堆栈和一个临时变量对堆栈进行排序。在排序函数中,当我尝试返回第二个堆栈的地址时,我不确定它返回的是什么类型。因为我遇到了两个错误:
file0.cpp: In function 'int main()':
file0.cpp:97:23: error: cannot convert 'int*' to 'stack*'
97 | arr.ad = sort(one.a);
和
file0.cpp:46:17: note: initializing argument 1 of 'int sort(stack*)'
46 | int sort(stack* obj){
| ~~~~~~~^~~
所以,这些是我遇到的错误。我通过将排序功能更改为:
stack* sort();
int* sort();
它们都不能正常工作。那么任何人都可以解释代码有什么问题并纠正它吗?为了不再犯此类错误,我必须更好地学习哪些主题?
#include <iostream>
#define MAX 101
using namespace std;
class stack{
public:
int top = -1, a[MAX];
int address;
void push(int x){
a[++top] = x;
}
void pop(){
top = top - 1;
}
bool isEmpty(){
if(top == -1){
return true;
}else{
return false;
}
}
int Top(){
return top;
}
void print(stack* arr){ //a function to print the stack just confirmaion
for(int i = 0; i < top; i++){ //that the stack is sorted
cout << arr->a[i];
}
}
};
int sort(stack* obj){ //function to sort the stack
int n = obj->top;
int temp = obj->a[n]; //a variable to hold the element
//if it is greater than the Top stack during sorting
stack two; //second stack for sorting the elements
if(two.isEmpty()){ //
two.push(temp);
}
while(obj->top != 0){
if((temp > obj->a[obj->top]) & (two.a[two.top] > temp)){
two.push(temp);
}else if(two.a[two.top] > obj->a[obj->top]){
two.push(obj->a[obj->top]);
obj->pop();
}else{
temp = obj->a[obj->top];
obj->pop();
obj->push(two.a[two.top]);
two.pop();
}
}
return two.a; //trying to return
//address of the second stack that I created
}
int main() {
stack one;
one.push(12); //pushing into the stack
one.push(1);
one.push(19);
one.push(14);
one.push(7);
one.push(79);
one.push(3);
stack* a;
a->address = sort(one.a);
one.print(a->address);
return 0;
}
```
【问题讨论】:
标签: c++ sorting oop pointers stack