关于C ++字符串的问题

问题描述 投票:1回答:2
phrase.erase(remove_if (phrase.begin(), phrase.end(), ::isdigit), phrase.end());

在上面的代码中,为什么我必须使用::即使我使用using namespace std

#include "Palindrome.h"
#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;

Palindrome::Palindrome (string Phrase){
    phrase=Phrase;
}

void Palindrome::removeNonLetters()
{
    phrase.erase(remove_if (phrase.begin(), phrase.end(), ::isdigit), phrase.end());

    phrase.erase(remove_if (phrase.begin(), phrase.end(), ::ispunct), phrase.end());

    phrase.erase(remove_if (phrase.begin(), phrase.end(), ::isspace), phrase.end());
}

void Palindrome::lowerCase()
{
    for (int i=0; i<phrase.length(); i++)
    {
        phrase[i] = tolower(phrase[i]); 
    }
}

bool Palindrome::isPalindrome()
{
    int length=phrase.length(); 
    int a=0;    
    for (int i=0;i<length/2;i++)
    { 
        if(phrase[i] != phrase[length-a-1])
        {
            return false;
            break;
        }
        a++;
    }
    return true;
}

上面的代码是检查字符串是否是回文。我不明白为什么我需要使用第一部分

Palindrome::Palindrome (string Phrase){
    phrase=Phrase;
}

如果我删除了上述部分,我将永远得到“是”。

主要的测试代码是

if(test.Palindrome::isPalindrome() == 1){
    cout<<"Yes"<<endl;
}
else {
    cout<<"No"<<endl;
}

还有一个问题。我尝试更改上面代码的小写,我收到错误。有谁知道它发生了什么?新代码来自https://www.geeksforgeeks.org/conversion-whole-string-uppercase-lowercase-using-stl-c/

之前

 void Palindrome::lowerCase()
{
    for (int i=0; i<phrase.length(); i++)
    {
        phrase[i] = tolower(phrase[i]); 
    }
}

void Palindrome::lowerCase(){

transform(phrase.begin(), phrase.end(), phrase.begin, ::tolower);

}

有谁可以向我解释一下?非常感谢!

c++ string palindrome
2个回答
2
投票

有多个isdigitispunctisspace函数 - 在<ctype.h>头中的全局命名空间中有一些,在std<cctype>头中的<clocale>命名空间中有几个。使用::对它们进行前缀表示您要使用全局命名空间中的那些。

您需要使用<string>而不是<string.h>才能使用std::string类。

假设testPalindrome对象,那么test.Palindrome::isPalindrome()应该只是test.isPalindrome()

如果省略Palindrome构造函数,则phrase成员保持空白,并且你的isPalindrome()实现返回true为空白phraselength为0)因为for循环没有任何内容可以检查。这在技术上是正确的 - 空白字符串是回文。


0
投票

::表示您正在使用isdigit和全局命名空间中的其他人。 isdigit是其他头文件的一部分,例如<ctype.h>

© www.soinside.com 2019 - 2024. All rights reserved.