12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++17 の構造化束縛を range-based for で使う

Posted at

ブログ記事からの転載です。

C++17 では構造化束縛という言語機能が追加されました。
これは std::tie のように std::tuple などを個別に変数で受け取る事が出来る機能です。

auto homu = std::make_tuple(1, "homu", 14);

// std::tuple の要素を個別に受け取る
auto [id, name, age] = homu;

std::tie とは違い変数定義で使用する事が出来ます。

range-based for で使う

これだけでも便利なのですが、range-based for と組み合わせることで更に便利になります。

#include <tuple>
#include <vector>
#include <string>
#include <iostream>

int
main(){
	std::vector<std::tuple<int, std::string, int>> vc = {
		{ 1, "homu", 14 },
		{ 2, "mami", 15 },
		{ 3, "mado", 14 }
	};
	for(auto&& [id, name, age] : vc){
		std::cout << "id:" << id << ", name:" << name << ", age:" << age << std::endl;
	}

	return 0;
}
/*
output:
id:1, name:homu, age:14
id:2, name:mami, age:15
id:3, name:mado, age:14
*/

こんな感じに range-based for の変数定義でも構造化束縛を使うことが出来ます。
ますます std::tuple が便利になりますね。

12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?