【问题标题】:String iterators and understanding a function字符串迭代器和理解函数
【发布时间】:2014-01-03 18:42:00
【问题描述】:
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();
}

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

// 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();

【问题讨论】:

  • 问题到底是什么?您似乎已经解释了代码...
  • 为了清楚起见,您想要解释什么?已经有 cmets 解释了选择的代码行
  • @KerrekSB 问题是帮助我理解代码的作用。我的解释是否正确,还是我的解释有误?我正在尝试了解它是如何工作的。
  • @Huytard 那些 cmets 是我写的,我想知道我是否解释得很好,它是否按照我描述的方式工作,还是我错了?
  • 您可能还对std::find_if感兴趣:return !s.empty() && s.end() == std::find_if(s.begin(), s.end(), [](char c){return !isdigit(c);});

标签: c++ string iterator


【解决方案1】:

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

// 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 为您提供迭代器“指向”的字符。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 2014-06-26
      • 2012-10-23
      • 2011-07-22
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2012-02-24
      相关资源
      最近更新 更多