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

时间:2016-06-21 03:42:53

标签: 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(), ',');
  }  
}

1 个答案:

答案 0 :(得分:1)

如果您想查找所有令牌并且您的程序没有提及,则需要将iterator提升到正确的位置,例如:

#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(), ',');
    }
}