while条件C++中声明中的奇怪行为
Strange behaviour in declaration inside a while condition C++
我正在C++中实现一个类似python的split()
函数来训练自己。我从这个SO线程中得到了这个想法:使用字符串分隔符(标准C++(在C++中解析(拆分(字符串
在此代码中:
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
值os pos
是在while
循环的条件内分配的。
我试过同样的方法:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
std::vector<std::string> split(std::string inp, std::string delimeter){
std::vector<std::string> res;
while (size_t pos = inp.find(delimeter) <= inp.length()){
std::cout << inp << " " << pos << std::endl ;
if (inp.substr(0, delimeter.length()) == delimeter) {
inp.erase(0, delimeter.length());
continue;
}
res.push_back(inp.substr(0, pos));
inp.erase(0, pos);
}
return res;
}
int main() {
for (auto i : split(",,ab,c,,d", ",")){
std::cout << i << " ";
}
std::cout << std::endl;
}
我的输出是:
,,ab,c,,d 1
,ab,c,,d 1
ab,c,,d 1
b,c,,d 1
,c,,d 1
c,,d 1
,,d 1
,d 1
a b c
我的问题是为什么它说,
在字符串,,ab,c,,d 1
中的位置是1
?
为什么ab,c,,d
中的位置也是1?
我修改了这样的代码:
#include <iostream>
...
size_t pos = 0;
while (pos <= inp.length()){
pos = inp.find(delimeter);
...
}
int main() {
for (auto i : split(",,ab,c,,d", ",")){
std::cout << i << " ";
}
std::cout << std::endl;
}
...
保持不变,现在它像符咒一样工作,输出为:
,,ab,c,,d 0
,ab,c,,d 0
ab,c,,d 2
,c,,d 0
c,,d 1
,,d 0
,d 0
d 18446744073709551615
ab c d
正如我所料。
所以我的问题是:为什么我不能在while条件中声明一个变量?是否在所有循环中都对条件进行了求值(因此声明再次发生?(即使在第一个循环中,我也得到了错误的结果1
。为什么?
while (size_t pos = inp.find(delimeter) <= inp.length()){
被解释为
while (size_t pos = (inp.find(delimeter) <= inp.length())){
而你需要一个完全不同的分组
while ((size_t pos = inp.find(delimeter)) <= inp.length()){
不过,后者在C++中是非法的。
不可能在while
条件中声明变量,同时使其参与更复杂的条件表达式(如与另一个值的比较(。当您在C++条件下声明一个变量时,您所能得到的只是它的初始值转换为bool。
修改后的代码在循环之前声明了pos
,从而正确地实现了您的意图。
相关文章:
- 当线程处理不同的类时,应该在哪里声明条件变量、互斥对象
- 有条件的使用声明
- 使用 decltype 的条件声明类型
- 条件类型声明
- 类声明自己(*this)为private以避免竞争条件/放弃在gcc中对threadprivate的请求
- 将静态 const 成员重新声明为 constexpr 是否会自动使其符合内联条件
- 可以在C 11中有条件声明的朋友类
- 可以在C 03中有条件地声明朋友类吗?
- 在此作用域中未声明条件变量函数
- 如何在 if 条件中声明变量
- (C++)如何基于条件声明对象类成员
- 在 FOR 循环语句的条件部分中使用声明
- 模板类中的条件引用声明
- 比较条件中的字符串,而不将它们声明为字符串
- 在条件中使用do-while循环内部声明的变量
- 声明不能发生在条件运算符表达式内部
- if条件中的C++静态和非静态变量声明
- 条件中声明的变量的作用域
- c++编译器如何处理在条件语句中声明的类型
- 在C++中使用if条件仅声明一个变量(模板)