0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】ユニーク要素を格納するコンテナの使い方

Posted at

開発を行っていると、コンテナの中に重複する要素を入れたくない…なんて時があるかと思います。
C++では、STLstd::setstd::unordered_setを使用することで、容易に実現することができます。
本記事では、std::unordered_setを使用し、ユニークな要素のみを格納するコンテナの使用方法を紹介したいと思います。

想定環境

  • C++11以上(std::setstd::unordered_setが使用可能になるバージョン)

コード例

unordered_set.cpp
#include <iostream>
#include <unordered_set>//要素がユニークなコンテナを使用するためのヘッダ
//---------------------------------------------------------------
//! @brief 要素がユニークなコンテナの要素をすべて出力する関数
//! @param set_like_container 要素がユニークなコンテナ
// ---------------------------------------------------------------
void ShowAllElements(const std::unordered_set<int>& set_like_container) {
	//範囲for文で要素をすべて出力
	for (const int& element : set_like_container) {
		std::cout << element << std::endl;
	}
}
//メイン関数
int main() {
	std::unordered_set<int> set_like_container;//要素がユニークなコンテナの宣言
	//要素の追加(試しに適当な値を)
	set_like_container.insert(1);
	set_like_container.insert(1);
	set_like_container.insert(10);
	set_like_container.insert(20);
	set_like_container.insert(10);
	ShowAllElements(set_like_container);//要素の出力
	//終了
	return 0;
	system("pause");
}
result
1
10
20

std::unordered_setはコンテナなので、テンプレート引数で格納したい要素の型を指定します(本記事ではint型)。

	std::unordered_set<int> set_like_container;//要素がユニークなコンテナの宣言

std::unordered_set内のinsertメンバ関数を使用することで、任意の値を要素に格納することができます。

	//要素の追加(試しに適当な値を)
	set_like_container.insert(1);
	set_like_container.insert(1);
	set_like_container.insert(10);
	set_like_container.insert(20);
	set_like_container.insert(10);

挿入時に同じ値を入れたにもかかわらず、値を順に出力した時に実行結果で値が重複していないことから、ユニークな値のみが挿入されていることが確認できると思います。

総括

  • std::setstd::unordered_setは、ユニークな値を格納するコンテナ。
  • insertメンバ関数を使用することで、値の挿入が可能。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?