Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 字符串迭代器与函数理解_C++_String_Iterator - Fatal编程技术网

C++ 字符串迭代器与函数理解

C++ 字符串迭代器与函数理解,c++,string,iterator,C++,String,Iterator,我有这个函数来检查字符串是否是数字。我在网上找到了这个片段,我想了解它是如何工作的 bool e_broj(const string &s){ string::const_iterator it = s.begin(); while(it != s.end() && isdigit(*it)){ ++it; } return !s.empty() && it == s.end(); } 你的理解几乎是对的。

我有这个函数来检查字符串是否是数字。我在网上找到了这个片段,我想了解它是如何工作的

bool e_broj(const string &s){
    string::const_iterator it = s.begin();
    while(it != s.end() && isdigit(*it)){
        ++it;
    }
    return !s.empty() && it == s.end();
}

你的理解几乎是对的。唯一的错误是在最后:

// this declares it as the beginning of the string (iterator)
string::const_iterator it = s.begin(); 

// this checks until the end of the string and
// checks if each character of the iterator is a digit?
while(it != s.end() && isdigit(*it)){ 

// this line increases the iterator for next
// character after checking the previous character?
++it;

// this line returns true (is number) if the iterator
// came to the end of the string and the string is empty?
return !s.empty() && it == s.end();
这应该是“并且字符串不是空的”,因为表达式是
!s、 empty()
,而不仅仅是
s.empty()

您可能只是把这句话说得很有趣,但要明确的是,
while
循环中的条件将使迭代器在字符串中移动,而它不在末尾,并且字符仍然是数字


你关于迭代器的术语让我觉得你并不完全理解它在做什么。您可以将迭代器看作是指针(实际上,指针是迭代器,但不一定相反)。第一行提供一个迭代器,它“指向”字符串中的第一个字符。执行
it++
将迭代器移动到下一个字符
s.end()
给出一个迭代器,该迭代器指向字符串末尾(这是一个有效的迭代器)<代码>*它提供迭代器“指向”的字符。

while循环在字符串的末尾或出现非数字时停止

因此,如果我们没有一直前进到末尾(
it!=s.end()
),那么字符串是非数字的,因此不是数字


空字符串是一种特殊情况:它没有非数字,但也不是数字。

问题到底是什么?你似乎已经解释了代码…只是想说清楚,你想要解释什么?已经有注释解释了选择的行code@KerrekSB问题是帮助我理解代码的作用。我解释得对吗,还是我的解释有误?我试图理解它是如何工作的。@Huytard这些评论是我写的,我想知道我是否解释得很好,它是按照我描述的方式工作的,还是我错了?你可能还对
std::find\u感兴趣,如果
返回!s、 empty()&&s.end()==std::find_if(s.begin(),s.end(),[](char c){return!isdigit(c);})
// this line returns true (is number) if the iterator
//  came to the end of the string and the string is empty?
return !s.empty() && it == s.end();