简体   繁体   中英

function returns an empty vector

I am trying to return a vector of strings from a function, but every time I do so I get an empty vector.However when I try to print the vector in the function itself it's not empty but when I try to print the returned vector I am getting nothing printed.

#include <iostream>
#include <vector>

using namespace std;
vector<string> permute(string S, string chosen){
    vector<string> permutated_strings;
    if(S.empty())
        permutated_strings.push_back(chosen);
    else{
         for(int i=0;i<S.length();i++){
            char c = S[i];
            chosen += c;

            S.erase(i,1);
            permute(S,chosen);

            //backtrack
            chosen.erase(chosen.length()-1,1);
            S.insert(i,1,c);
        }
    } 
    return permutated_strings;
}

int main() {
    //code
    int test;
    cin >> test;
    while(test)
    {
        string S;
        cin >> S;
        vector<string> vec;
        vector<string> ::iterator i;
        vec = permute(S,"");
        for(i=vec.begin();i!=vec.end();i++)
            cout<<*i<<" ";
        cout << "\n";
        test--;
    }
    return 0;
}

When I am printing the vector in the permute function I am getting the right result but when I am printing the vector in main function it is empty. Can somebody please point me out the mistake I am doing.

You need to save result of recursive call of permute method.

auto result = permute(S,chosen);
permutated_strings.insert(permutated_strings.end(), result.begin(), result.end());

I got the mistake that I was doing. I really hate answering my own questions but it may help someone like me in the future.

I have changed -

vector<string> permutated_strings;

to

static vector<string> permutated_strings;

in the permute function so that previous returns from the recursive calls are not lost. By doing so I am getting the desired result.

Thanks everyone for pointing me to the mistake that I was doing.

EDIT

As suggested by @MM that this solution may cause problem in future. And I have realized that if I give "test" value as 2 the final value in the permutated_strings will be from test=1 + test =2 which is not which I wanted. So this solution is not the perfect one. Instead I am accepting solution from @BartekPL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM