字符串迭代器和理解函数
String iterators and understanding a function
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()
),那么字符串是非数字的,因此不是数字。
空字符串是一种特例:它没有非数字,但也不是数字。
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 如何创建迭代器函数
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- 使用迭代器的模板类的构造函数
- C++:复制迭代器的构造函数
- 基于函数而不是集合的二分搜索或迭代器?
- 成员函数中的迭代器出现问题
- 使用迭代器的自定义比较器函数
- 专门C++使用指针值类型的通用迭代器的模板函数?
- 从 std::vector 迭代器中执行函数指针
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 如何基于循环迭代器选择函数
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 具有C++迭代器参数的多功能函数
- C++如何获取传递给函数(STL 迭代器)的参数的名称
- C++ 解释重载成员函数迭代器(int i = 0) 的构造"one liner":i(i) { };