C++ 为什么迭代器在与 find 函数一起使用时表现不同?

标签 c++ c++11 vector

为什么在 while 循环中每次构造 it1 时,下面的代码片段都会表现得很奇怪?在 VS 2015 中,循环不会终止。使用 gcc 4.9,它在第一个字之后打印空字。如果我不在 while 循环内构造 it1,循环是否按预期工作?迭代器是否进行某种惰性求值?

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
int main () { 

  std::string S("Hello world, the, quick, brown, fox, jumps, over");

  std::vector<char> V(S.begin(), S.end());
  std::vector<char>::const_iterator it = V.cbegin();
  std::vector<char>::const_iterator it1 = std::find(it, V.cend(), ',');

  while (it1 != V.cend()) {
    std::cout <<"the string is: " << std::string(it, it1) << std::endl;
    it = ++it1;
    std::vector<char>::const_iterator it1 = std::find(it, V.cend(), ',');
    //it1 = std::find(it, V.cend(), ',');
  }  
}

最佳答案

如果你想找到所有的标记并且你的程序没有循环,你需要将迭代器推进到正确的位置,例如:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

int main () {
    std::string S("Hello world, the, quick, brown, fox, jumps, over,,");

    std::vector<char> V(S.begin(), S.end());
    std::vector<char>::const_iterator it = V.cbegin();
    std::vector<char>::const_iterator it1 = std::find(it, V.cend(), ',');

    while (it != V.cend()) {
        std::cout << "The string is: " << std::string(it, it1) << std::endl;
        it = ++it1;
        it1 = std::find(it, V.cend(), ',');
    }
}

关于C++ 为什么迭代器在与 find 函数一起使用时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37935187/

相关文章:

c++ - 在 cmake C++ 项目中使用 mongodb cxx 驱动程序

C++ std::vector 在头文件中初始化和设置

c++ - 涉及将 vector 转换为 feed 到 execvp 的错误类型

c++ - 如何防止相机 vector 中的浮点错误

c++ - 如何在Mandelbrot集中放大光标点?

c++ - 创建从 STL 集继承的新类的错误

r - 找到两个不同长度的向量之间的所有组合

c++ - 如何阻止Clang发出数百条有关应聘者的消息?

c++ - 如何删除 "completely"链表中的所有节点?

c++ - C++ shared_ptr::operator* 危险吗?