bool hasWord(int y, int x, string &word) {
if(!inRange(y, x)) return false;
if(board[y][x] != word[0]) return false;
if(word.size() == 1) return true;
for(int direction = 0; direction < 8; direction++) {
int nextX = x + dx[direction];
int nextY = y + dy[direction];
if(hasWord(nextY, nextX, word.substr(1))) // <--- This
return true;
}
return false; }
error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘std::basic_string’ if(hasWord(nextY, nextX, word.substr(1)))
why the reason I was wrong?
The error message says it all: invalid initialization of non-const reference of type std::string
{aka std::basic_string
} from an rvalue of type std::basic_string
.
I.e. a reference to non-const cannot be bound to a temporary object (aka r-value). That temporary object is created by word.substr(1)
expression.
In declaration:
bool hasWord(int y, int x, string &word)
Make it string const& word
, since you do not need a modifiable word
.
The reason of the error is that in this call
if(hasWord(nextY, nextX, word.substr(1)))
^^^^^^^^^^^^^^
there is created a temporary object of the type std::string and you are trying to bind a non-constant reference with the temporary object.
If the string is not changed in the function then just declare the function like
bool hasWord(int y, int x, const string &word) {
^^^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With