字符串迭代器和理解函数

String iterators and understanding a function

本文关键字:函数 迭代器 字符串      更新时间:2023-10-16
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();

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

// 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() 给出一个迭代器,该迭代器指向字符串末尾(这是一个有效的迭代器)。 *it为您提供迭代器"指向"的字符。

当出现非数字时,while 循环在字符串 OR 处停止。

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

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