【问题标题】:String iterator never reaches std::string::end()字符串迭代器永远不会到达 std::string::end()
【发布时间】:2020-01-16 17:04:31
【问题描述】:

使用 const 迭代器遍历字符串时,它永远不会结束。在遍历期间从不修改字符串。但是itr 永远不会到达src.cend()。最后程序崩溃了。

此功能是将域名转换为标准域名以进行DNS查询。例如,www.abc.com 转换为 3www3abc3com。

string name_hton(const string &src) {
  string dst;

  auto itr = src.cbegin(), last = itr;

  do {
    while (itr != src.cend() && *itr != '.') {
      ++itr;
    }

    auto diff = itr - last;

    // Push the label length
    dst.push_back(diff);

    // Push the label
    dst.append(last, itr);

    ++itr;
    last = itr;
  } while (itr != src.cend());

  return dst;
}

【问题讨论】:

  • 是时候用你的调试器逐步完成它了。
  • @Nico238 这不是格式错误

标签: c++ string iterator


【解决方案1】:

我建议使用std::string::find() 而不是手动搜索循环:

string name_hton(const string &src) {
    string dst;

    auto idx = src.find('.'), last = 0, diff;
    while (idx != string::npos) {
        diff = idx - last;
        dst.push_back(static_cast<char>(diff));
        dst.append(src, last, diff);
        last = idx + 1;
        idx = src.find('.', last);
    }

    diff = src.size() - last;
    dst.push_back(static_cast<char>(diff));
    dst.append(src, last, diff);

    return dst;
}

【讨论】:

    【解决方案2】:

    您的代码将位于字符串的末尾。

    当您在字符串中找到最后一个'.',并且外部循环迭代您的内部循环时,您的内部循环将以itr == src.cend() 结束。然后您将递增该迭代器(这是错误的)并且外部循环条件将不再为真。

    如果++itr 不等于src.cend(),您应该只在外循环中执行。

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 2016-06-22
      • 2016-02-12
      • 2017-01-07
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      相关资源
      最近更新 更多