简体   繁体   English

'islower'的重载无效

[英]Invalid overload of 'islower'

I'm trying to develop the BattleShip game in C++ and I'm almost done. 我正在尝试用C ++开发BattleShip游戏,我差不多完成了。 For that, I need my gameOver function working. 为此,我需要我的gameOver功能正常工作。 My game is over when all the ships are sunk. 所有的船都沉没了,我的游戏结束了。 Therefore, I'm trying to count how many lowercase chars I have in my string status (from Ship). 因此,我正在尝试计算我的字符串状态(来自Ship)中有多少个小写字符。 When half of the chars are lowercase, the "ship" is destroyed and I'm ready to use my gameOver function. 当一半的字符是小写字母时,“船”被破坏,我准备使用我的gameOver功能。

But somehow my count_if isn't working and I don't know why. 但不知怎的,我的count_if不起作用,我不知道为什么。

Here you go: 干得好:

#include <algorithm>

bool Ship::isDestroyed() const{ 
    //This counts those chars that satisfy islower:
    int lowercase = count_if (status.begin(), status.end(), islower); 
    return ( lowercase <= (status.length/2) ) ? true : false;
}

bool Board::gameOver() {
    bool is_the_game_over = true;
    for(int i = 0 ; i < ships.size() ; i++){
        if( ships[i].isDestroyed() == false ) {
            //There is at least one ship that is not destroyed.
            is_the_game_over = false ;
            break;
        }
    }
    return is_the_game_over;
}

What am I doing wrong? 我究竟做错了什么?

Unfortunately, the standard library has more than one overload of islower (a function from the C library, and a function template from the localisation library), so you can't simply name the function unless you're calling it. 不幸的是,标准库有多个islower重载(来自C库的函数,以及来自本地化库的函数模板),所以除非你调用它,否则你不能简单地命名函数。

You could convert it to the right function type: 您可以将其转换为正确的函数类型:

static_cast<int (*)(int)>(islower)

or hope that your implementation dumps the C library into the global namespace as well as std : 或希望您的实现将C库转储到全局命名空间以及std

::islower      // not guaranteed to work

or wrap it in a lambda 或将其包裹在lambda中

[](int c){return islower(c);}

Try to change the algorithm call the following way 尝试按以下方式更改算法调用

int lowercase = count_if (status.begin(), status.end(), ::islower); 
                                                        ^^^

The compilers are allowed to place standard C functions in the global namespace. 允许编译器将标准C函数放在全局命名空间中。

Otherwise use a lambda expression as for example 否则使用lambda表达式作为例如

int lowercase = count_if (status.begin(), status.end(), 
                          []( char c ) return islower( c ); } ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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