0
我有這個問題,我開始使用這個函數後程序崩潰了。我不知道如何正確返回所需的類型。它是模板中的二進制搜索。我試着將它更改爲T * search,將array[middle]
轉換爲const並執行諸如const T * out = &array[middle];
之類的操作,但是每當我添加&時,它都會崩潰。如果我把它拿回來,只返回數組[中],它說:const T * search(const T&)return not working
cannot convert 'Fractions' to 'const Fractions*' in return
我應該如何正確地返回它? 我有這樣的數組聲明和這個函數是在同一個類:它應該與任何類型的工作,我們被給予類分數來測試它,所以它正常的類型分數組,沒有什麼幻想。
T * array;
和
const T *search(const T &inElement){
unsigned low = 0;
unsigned high = numberOfElements-1;
unsigned middle = 0;
while(low <= high){
middle = low + (high - low)/2;
if(inElement == array[middle]){
const T * out = &array[middle]; //problem here
return out;
}
else if(inElement < array[middle]){
high = middle -1;
}
else{
low = middle + 1;
}
}
return NULL;
}
指針和引用總是問題對我來說,我讀到類似主題的回合這個向量和斜面還是理解它。
我班的其餘部分:
#include <iostream>
#include "Fractions.cpp"
using namespace std;
template<class T,unsigned n>
class SortedArray {
T * array;
unsigned length;
unsigned numberOfElements;
T element;
unsigned position;
public:
SortedArray() {
length = n;
array = new T[n];
numberOfElements = 0;
position = 0;
}
bool first(){
if(numberOfElements >= 1){
element = array[0];
position = 0;
return true;
}
return false;
}
bool next(){
if(position+1 < numberofElements){
position++;
element = array[position];
return true;
}
return false;
}
const T & aktual(){
return element;
}
SortedArray & operator << (const T &element){
if(numberOfElements == length || search(element) == NULL){return (*this);}
if(numberOfElements == length){return (*this);}
int i = numberOfElements;
for (; i > 0 && array[i-1] > element; i--)
{
array[i] = array[i-1];
}
array[i] = element;
numberOfElements++;
return (*this);
}
operator unsigned() const{
return numberOfElements;
}
const T *search(const T &inElement){
//this is the function causing problems
}
~SortedArray() {
delete [] array;
array = NULL;
}
};
int main()
{
SortedArray<Fractions,20> pz;
typedef Fractions Z;
pz << Z(1,3) << Z(3,5) << Z(7,4) << Z(3,4) << Z(2,3) << Z(7,2)
<< Z(5,4) << Z(1,4) << Z(6,7) << Z(4,3) << Z(2,3);
cout << "\nNumber of elements : " << pz.operator unsigned() << endl;
return 0;
}
沒有足夠的代碼上下文來告訴! –
'array'的類型是什麼? –
數組來自哪裏?你可以發佈一些代碼嗎? – splrs