2016-04-28 13 views
-1

2つの引数、つまり配列とキー値を取り、その値がキーと一致するかどうかを再帰的に調べる関数を作成しようとしていました。C++での再帰的リスト操作

これを達成するには、配列が空であるかどうかを確認する必要があります。私はまた、私の再帰関数で配列を呼び出す方法が必要です。私は助けるためにスタックオーバーフローで何かを見つけることができませんでしたが、私はこのCheck if list is empty in C#ポストで提案された方法を試して、コードがエラーを与えました。

TLDR配列が空であるかどうかを調べる方法と、配列をパラメータとして受け取る関数を再帰呼び出しする方法を理解する必要があります。

// recursive method: increment count for each recursive call; return the value of count when the key matches the value, then decrement count on 
int Search::ReKeySearch(int arr[], int key){ 
//bool isEmpty = !list.Any(); tried to use this code, found on StackExchange, gave following error: "Cannot refer to class template 'list' without a template argument list" 

if (arr[count] == 0){ //if the key matches the list index's value 
    store = count; // so that I can reset count to zero, I use a storing variable 
    count = 0;  // count should always be zero on exiting or entering a function 
    return store; 
} 

else{ 
    count++; 
    if (/*need to check if list is empty*/){ 
     ReKeySearch(arr[1:], key); //recursive call to function on list after zeroth member 
             //returns error "expected ']'", pointing to the colon 
     }// using pointer to attack problem of list index 
    else 
     ; 
    count--; 
} 
if (count == 0) 
    return -1; 

}

+2

この 'arr [1:]'は私のC++コードのようには見えません。 –

+0

彼らはたぶん 'arr + 1'と言っていました。 – paddy

+0

テンプレート関数を書いて0を大文字にするか、単にstd :: vectorを使うことができます – Incomputable

答えて

0

はもちろん、私はあなたが再帰的にそれをやってみたいことを推測しています、単純なループで、このようなタスクを達成することができますが。私は次のようにします。実験したい場合はlinkです。

#include <iostream> 
#include <vector> 
using namespace std; 

int searchHelper(const int arr[], int start, int stop, int key) 
{ 
    if(start == stop) return -1; 
    if(arr[start] == key) return start; 
    return searchHelper(arr, start + 1, stop, key); 
} 

int search(const int arr[], int size, int key) 
{ 
    return searchHelper(arr, 0, size, key); 
} 

int search(vector<int> const& vec, int key) 
{ 
    return searchHelper(vec.data(), 0, (int)vec.size(), key); 
} 

int main() { 
    int arr[] = {3,10,2,5,6,1}; 

    cout << search(arr, 6, 10) << endl; 
    cout << search(arr, 6, 20) << endl; 

    return 0; 
} 

私は2つのアプローチを提供しました.1つはSTLベクターを使用する別の配列です。ベクトルでは、配列のサイズを別々に保つ必要はありません。配列がソートされている場合は、同様の手法を使用してバイナリ検索を行うことができます。