c++ - 一段时间内声明中的奇怪行为 C++

标签 c++ while-loop

我正在用 C++ 实现类似 python 的 split() 函数来训练自己。我从这个 SO 线程中得到了这个想法:Parse (split) a string in C++ using string delimiter (standard 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 poswhile 循环的条件内赋值。

我试过同样的事情:

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

关于c++ - 一段时间内声明中的奇怪行为 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40023388/

相关文章:

swift - 使用闭包作为 While 循环的条件

c++ - 不使用线程的并行 while 循环

c++ - 无法在 Watch 窗口中计算具有重载运算符的表达式

c++ - void() 函数返回一个值而不是 char 或 string?

c - 如何修复这个简单的 do/while 循环?

c++ - 计算c++密码程序的循环

c++ - while 循环外的变量在重新分配时变为 NULL

仅在没有优化的情况下编译时出现 C++ 错误 (GCC)

c++ - cpp中的指针

c++ - 具有两级指针的 const_cast