我在C++中實現了一個像Python一樣的split()
函數來訓練我自己。我從這個SO線程的想法:Parse (split) a string in C++ using string delimiter (standard 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
我的問題是,爲什麼它POES說的,
字符串,,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()){
後者是用C++非法雖然
您對第一個代碼示例的陳述是錯誤的。這讓問題變得混亂!已在循環之前聲明瞭「pos」。 – juanchopanza
在第一個代碼中,「pos」沒有在for循環中聲明。它應該在某個地方被宣佈。 – NathanOliver
「爲什麼不能在一段時間內聲明一個變量?」您可以。只要記住變量的作用域在循環的每次迭代時都會被重置 – UKMonkey