C 与查找功能一起使用时,迭代器为什么行为会有所不同
C++ Why does the iterators behave differently when used with the find function?
为什么每次在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(), ',');
}
}
,如果您想找到所有令牌,并且您的程序没有cicle,则需要将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(), ',');
}
}
相关文章:
- 为什么output_editor Concept不需要output_e迭代器标记
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 为什么以及如何C++更改旧迭代器的值
- 为什么迭代器没有到达向量末端?
- 为什么迭代器调试在调试版本中会减慢 std::unordered_map 200 倍?
- 为什么迭代器不返回集合的开头
- 为什么迭代器类型与矢量容器中的 value_type * 不匹配
- 为什么迭代器运算符 + 返回副本
- 为什么迭代器指向的数据在从列表中删除后保留
- 为什么迭代器定义为结构而不是类
- 为什么迭代器在与map.begin()一起使用时预先增加了
- 为什么迭代器::end()是非静态成员,与字符串::npos不相似
- 嵌套迭代器循环,为什么迭代器是相等的?——c++
- 为什么迭代器不兼容
- 为什么迭代器被标记为值对象,而被引用为指针?
- 为什么迭代器向量::插入在填充后无效:迭代器插入(const_iterator位置,size_type n,常量value_type和val);
- 为什么迭代器类型演绎失败
- 为什么迭代器在容器调用分配时不能引用它们所属的容器?