【问题标题】:c++ string iteratorc++ 字符串迭代器
【发布时间】:2011-07-22 07:47:46
【问题描述】:

我正在尝试在一个循环中使用一个迭代器对字符串执行 if 语句,但不知道如何获取 if 语句的当前字符:

for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i) {
    if (!isalpha(*i) && !isdigit(*i)) {
        if(i != "-") { // obviously this is wrong
            buffer.erase(i);
        }
    }
}

有人可以帮我获取当前字符,以便我可以做一些额外的 if 语句吗?

【问题讨论】:

  • 如果您之后要检查特定字符,则不需要 isalpha 和 isdigit 检查

标签: c++ string iterator


【解决方案1】:

我不知道如何获取当前字符

你在这里做了两次:

if (!isalpha(*i) && !isdigit(*i))

当您取消引用迭代器 (*i) 时,您将获得它指向的元素。

"-"

这是一个字符串文字,而不是一个字符。字符常量使用单引号,例如'-'

for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i)

使用反向迭代器会更简单:

for (std::string::reverse_iterator i = buffer.rbegin(); i != buffer.rend(); ++i)

【讨论】:

  • if((*i) != '-')) 如果您需要更多说明
  • @P.R.:"-" 很好。
  • @James 谢谢 :) 我曾经是 C++ 课程的实验室讲师,我想现在我首先看到的是 '' 和 ==
  • 使用reverse_iterator 迭代会更简单,但使用erase 元素会更简单。
  • @David Rodríguez 虽然使用前向迭代器使erase 更简单,但它也使循环非法,因为它将迭代器递减到begin 之前。
【解决方案2】:

要获得角色,只需说*i,但这还不够。您的循环是不合法的,因为它不允许在 begin 之前递减。您应该使用反向迭代器或remove_if 算法。

【讨论】:

    【解决方案3】:

    您在前面的if 语句中已经有了它:i 是一个迭代器,所以*i 给出了迭代器引用的字符。

    请注意,如果您要向后遍历集合,通常使用reverse_iteratorrbeginrend 会更容易。不过,我可能会使用预先打包的算法。

    【讨论】:

      【解决方案4】:
      if(i != "-")
      

      应该是

      if(*i != '-')
      

      【讨论】:

        【解决方案5】:

        其他答案已经解决了您遇到的特定问题,但您应该知道有不同的方法可以解决您的实际问题:删除满足条件的元素。这可以通过 remove/erase 习语轻松解决:

        // C++0x enabled compiler
        str.erase( 
            std::remove_if( str.begin(), str.end(), 
                          [](char ch) { return !isalpha(ch) && !isdigit(ch) && ch != '-' } ),
            str.end() );
        

        虽然这可能一开始看起来很麻烦,但一旦你看到它几次就不会感到惊讶了,它是从向量或字符串中删除元素的有效方法。

        如果您的编译器不支持 lambda,那么您可以创建一个仿函数并将其作为第三个参数传递给 remove_if

        // at namespace level, sadly c++03 does not allow you to use local classes in templates
        struct mycondition {
           bool operator()( char ch ) const {
              return !isalpha(ch) && !isdigit(ch) && ch != '-';
           }
        };
        // call:
        str.erase( 
            std::remove_if( str.begin(), str.end(), mycondition() ),
            str.end() );
        

        【讨论】:

          猜你喜欢
          • 2015-07-04
          • 2012-10-23
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          • 2021-04-01
          • 2011-02-24
          • 2017-12-15
          • 1970-01-01
          相关资源
          最近更新 更多