Search code examples
c++c++14cppcheck

not able to reverse operation. The error that says it cannot convert void to string but my result is saved as string. Have shown the code to refer


string result;
for(int i=st.size()-1;i>=0;i--){
 result+=st.top();
 cout<<st.top()<<endl;
 st.pop();}
 result+='\0';
 return reverse(result.begin(), result.end());

st is a stack of character. I want to output stack elements in reverse order


Solution

  • The return value of std::reverse() is void, so you can't return it (except from a function that itself returns void).

    std:reverse() modifies the contents of the input range inline, so just return the std::string variable whose characters you are asking std::reverse() to modify, eg:

    string result;
    while (!st.empty()){
        result += st.top();
        cout << st.top() << endl;
        st.pop();
    }
    reverse(result.begin(), result.end());
    return result; // <-- here
    

    Alternatively, you could just use string::insert() instead and not use std::reverse() at all, eg:

    string result;
    result.reserve(st.size());
    while (!st.empty()){
        result.insert(0, st.top());
        cout << st.top() << endl;
        st.pop();
    }
    return result;