william_
william_

Reputation: 1133

returning multiple values from recursive function c++

i have a recursive search function that returns the index of my vector where the search key was found However sometimes my vector can have two different positions that have the same key but my function only returns the first one.

here is my function:

int IdeaBank::twoSearchAND(int first, int last, string word_1, string word_2)
{
    if (last == first)
        return -1;

    if (newIdea[first].foundWordInBoth(word_1)
     && newIdea[first].foundWordInBoth(word_2))
        return first;       
    else 
        return twoSearchAND(first+1,last,word_1,word_2);
}

and here is how i am using it in my main

int first = 0;
int last = ideaBank.newIdea.size();
int index_found;
index_found = ideaBank.twoSearchAND(first, last, search_word1, search_word2);
ideaBank.displayIdeaByID(index_found);

my idea was to loop through n amount of times were n is the number of index's it returns but i wasnt too sure how to achieve that is there a way for me to get all the returned values from my function?

Edit: this is for a school project and must use recursion

Upvotes: 0

Views: 840

Answers (2)

Jarod42
Jarod42

Reputation: 217235

You might collect results into a container such as std::vector.

To avoid extra copies to concatenate vectors if used as return value, I use it as output parameter in the recursive method.

void IdeaBank::twoSearchAND(int first, int last,
                            const std::string& word_1, const std::string& word_2,
                            std::vector<int>& res)
{
    if (last == first)
        return;

    if (newIdea[first].foundWordInBoth(word_1)
     && newIdea[first].foundWordInBoth(word_2))
        res.push_back(first);
    twoSearchAND(first + 1, last, word_1, word_2, res);
}

std::vector<int> IdeaBank::twoSearchAND(const std::string& word_1,
                                        const std::string& word_2)
{
    std::vector<int> res;

    int first = 0;
    int last = newIdea.size();

    twoSearchAND(first, last, word_1, word_2, res);
    return res;
}

And usage is similar to:

auto indexes_found = ideaBank.twoSearchAND(search_word1, search_word2);
for (auto index_found : indexes_found) {
    ideaBank.displayIdeaByID(index_found);
}

Upvotes: 1

eerorika
eerorika

Reputation: 238321

A function can return at most one value. However, a class can have multiple sub objects. Therefore you can return multiple sub objects within one return by returning a class. To return exactly two values, you can use std::pair for example.

Note that this algorithm is already in the standard libarary: std::search_n, so there is no need to re-write it. Also, it is an inherently iterative algorithm and there is no need to complicate it by using recursion.

Upvotes: 5

Related Questions