Home > Back-end >  Error:variable has incomplete type 'void'
Error:variable has incomplete type 'void'

Time:03-01

#include <algorithm>
 std::string  reverse_words(std::string str)
{

  auto rvsword = std::reverse(str.begin(), str.end());
 return rvsword;
 }

I decided to solve the task on codewars on the reverse line, but an error comes out, what should I do?

CodePudding user response:

std::reverse returns nothing. So, it cannot be used to assign a value.

To fix your code, since your input is passed by copy, simply call the reverse function, then return str:

#include <algorithm>
std::string reverse_words(std::string str)
{

 std::reverse(str.begin(), str.end());
 return str;
}

CodePudding user response:

The standard algorithm std::reverse is declared like

template<class BidirectionalIterator>
void reverse(BidirectionalIterator first, BidirectionalIterator last);

That is its return type is the incomplete type void.

So you may not initialize a variable with void.

auto rvsword = std::reverse(str.begin(), str.end());

Also there is no a great sense to define a function that all what it does is calls the algorithm.

Nevertheless the function can be declared and defined the following way

std::string & reverse_words( std::string &str )
{
    std::reverse( str.begin(), str.end() );
    return str;
}

Or if you need to create a new string reversed relative to another string then you could just write

std::string reverse_words( const std::string &str )
{
    return { str.rbegin(), str.rend() };
}
  • Related