私は自分自身を鍛えるためにC++でsplit()
関数のようなPythonを実装しています。このコードでParse (split) a string in C++ using string delimiter (standard C++)while条件内の宣言での不思議な動作C++
:私はこのSOスレッドから着想を得た
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
pos
OSが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
で,
の位置が1
であると言う理由ライセンス証書
,,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であるのですか?
私はこのようなコード変更:
#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
で間違っています。何故ですか?
最初のコードサンプルに関する記述が間違っています。そしてそれは疑問を混乱させます! 'pos'はループの前に宣言されています。 – juanchopanza
最初のコードでは、 'pos'はforループで宣言されていません。それはその前にどこかで宣言されています。 – NathanOliver
"while条件内で変数を宣言できないのはなぜですか?"あなたはできる。ループの各繰り返しで変数のスコープがリセットされることを覚えておいてください。 – UKMonkey