早期終了とスキップ
Coddyの「Python開発者のためのC++」コースのレッスン 10/48。
Pythonはloop-elseをサポートしていますが、このC++の例もその課題も使用していません。C++のbreakとcontinueは、最も内側のループを制御します。C++のbreakは最も内側のループを終了し、continueは次の反復に進みます。インクリメントをスキップするcontinueの前に、手動で管理しているインデックスを進めてください。
Python
words = ["red", "", "blue", "STOP", "green"]
for word in words:
if word == "STOP":
break
if not word:
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";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Python開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ