setの良い点は、findによって目的のオブジェクトがsetに含まれているかどうかすぐに判別できる点であり、ソートされて保持された性質を利用して、ソート用途としてsetを使ってはならない。vectorをalgorithm sortでソートするよりもオーバーヘッドが高いからである。オーバーヘッドは、setが指定した要素をfindですぐに見つけられるように要素をinsertする際にインデックスすることからも想像に難くない。
また、ソートされることからわかるように、setの要素となる型にはオペレータ < が定義されている必要がある。これはmapのキーと同じである。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// set.cpp | |
// CplusplusPractice | |
// | |
// Created by masai on 2015/05/25. | |
// Copyright (c) 2015年 masai. All rights reserved. | |
// | |
#include <iostream> | |
#include <set> | |
using namespace std; | |
int main(int argc, char* argv[]){ | |
set<int> s; | |
// insert | |
s.insert(1); | |
s.insert(2); | |
s.insert(3); | |
s.insert(4); | |
s.insert(5); | |
// setの要素数 | |
cout << "set cnt is " << s.size() << endl; | |
// 保持している要素は、iteratorを受け取ることができる | |
set<int>::iterator i = s.find(3); | |
if(i == s.end()){ | |
cout << "can not find." << endl; | |
}else{ | |
cout << "find " << *i << endl; | |
} | |
// 保持していない要素は、iterator end()を受け取ることができる | |
set<int>:: iterator i_c = s.find(10); | |
if(i_c == s.end()){ | |
cout << "can not find 10" << endl; | |
}else{ | |
cout << *i << endl; | |
} | |
// 要素の削除 | |
s.erase(3); | |
set<int>:: iterator i_e = s.find(3); | |
if(i_e == s.end()){ | |
cout << "can not find 3" << endl; | |
}else{ | |
cout << *i << endl; | |
} | |
// setの要素数 | |
cout << "set cnt is " << s.size() << endl; | |
} |
0 件のコメント:
コメントを投稿