while条件C++中声明中的奇怪行为

Strange behaviour in declaration inside a while condition C++

本文关键字:声明 条件 C++ while      更新时间:2023-10-16

我正在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,从而正确地实现了您的意图。