早期終了とスキップ
Coddyの「Dart開発者のためのC++」コースのレッスン 10/48。
DartのbreakとcontinueはC++と同じように動作しますが、break outer;のようなDartのラベル付きループの終了には、C++に直接対応するものがありません。代わりに、関数から戻るかフラグを使います。C++のbreakは最も内側のループを終了し、continueは次の反復に進みます。continueによってインクリメントが飛ばされる場合は、手動で管理しているインデックスを先に進めてください。
Dart
void main() {
var words = ['red', '', 'blue', 'STOP', 'green'];
var i = 0;
while (i < words.length) {
var word = words[i++];
if (word == 'STOP') break;
if (word.isEmpty) continue;
print(word);
}
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
std::vector<std::string> words={"red","","blue","STOP","green"};size_t i=0;while(i<words.size()){auto word=words[i++];if(word=="STOP")break;if(word.empty())continue;std::cout<<word<<"\n";}
}
それぞれのプログラムを個別に追跡してください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースとターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力:空白区切りの整数。最初のゼロより前にある正の値を合計し、負の値はスキップし、ゼロより後の値は無視します。
exercise.hpp と exercise.cpp で宣言されている API を実装してください。両方のファイルを編集できます。公開シグネチャは変更しないでください。ロックされている main.cpp は標準入力を読み取り、API を直接呼び出します。また、指定されている箇所では公開 API の動作も個別に検証します。API 内では値を返し、出力はしないでください。整数の入力値と結果は符号付き int の範囲内です。特に指定がない限り、テキストは ASCII です。
自分で試してみよう
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<int> v;int n;while(in>>n)v.push_back(n);std::cout<<positive_prefix(v)<<"\n";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Dart開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ