集合と要素の判定
Coddyの「C開発者のためのC++」コースのレッスン 15/48。
Cで一意性を確認するには、バッファをスキャンしたり、独自のハッシュテーブルを使ったりすることがよくあります。C++のstd::setは、各キーのコピーを1つだけ、ソートされた順序で保持します。挿入時には、そのキーが新しいものだったかどうかが報告されます。コンテナの順序は、挿入順ではなく、キーの比較関数を使います。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main(void){
int values[]={8,3};bool found=false;for(int i=0;i<2;i++)if(values[i]==8)found=true;puts(found?"false true":"unexpected");
return 0;
}
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::set<int> s{8,3};std::cout<<std::boolalpha<<s.insert(8).second<<" "<<s.insert(5).second<<"\n";
}
各プログラムを個別に追跡しましょう。これらの例では、課題とは異なる操作やデータを使って概念を示しています。ソースの出力と目標の出力が一致するとは限りません。
チャレンジ
簡単入力:整数。異なる値の個数を返してください。
exercise.hpp と exercise.cpp で宣言されている API を実装してください。両方のファイルを編集できます。公開シグネチャは変更しないでください。ロックされた main.cpp は stdin を読み取り、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<<unique_count(v)<<"\n";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ