[英]find() usage in C++ stl
我一直在實現C ++ STL set<>
,但是在使用find()
函數時遇到了麻煩。
下面是我的set<>
類型,因此我可以存儲三個整數a,b,c。
set<pair<int,pair<int,int> > > myset;
1)如何在其中使用find()
。“我是否需要像在sort()中那樣在這里傳遞自己的比較器函數”。
2)還有set<>
如何保持set<>
的唯一性。 我的意思是我想要包含
{ {1,2,3}; {2,3,4} ; {2,3,1} }
{ {1,2,3}; {2,3,4} ; {2,3,1} }
元素,如果我插入:
{1,2,3}
{2,3,4}
{1,2,3}
{2,3,1}
您可以使用元組而不是pair <int,pair>嗎? (請參見答案末尾)
如果不能(因為您未使用C ++ 11),則可以將find與您的對一起使用,則不需要比較器:
typedef pair<int,pair<int,int>> my_type;
typedef set<my_type> set_of_mytype;
set_of_mytype myset;
myset.insert(make_pair(1,make_pair(3,4)));
set_of_mytype::iterator search1 = myset.find(make_pair(1,make_pair(5,4)));
set_of_mytype::iterator search2 = myset.find(make_pair(1,make_pair(3,4)));
if(search1 != myset.end())
cout << "search 1: (1,(5,4)) found !" << endl;
if(search2 != myset.end())
cout << "search 2: (1,(3,4)) found !" << endl;
cout << " Size of the set with only (1,(3,4)) in it : "<< myset.size() << endl;
myset.insert(make_pair(3,make_pair(1,4)));
cout << " Size of the set with only (1,(3,4)) and (3,(1,4)) in it : "<< myset.size() << endl;
將輸出:
搜索2:找到(1,(3,4))!
僅包含(1,(3,4))的集合的大小:1
僅包含(1,(3,4))和(3,(1,4))的集合的大小:2
因此,對於您的第一個問題:沒有自定義比較器,它將起作用。
對於第二個,如果您嘗試再次插入:
myset.insert(make_pair(1,make_pair(3,4)));
cout << " Size of the set is still : "<< myset.size() << endl;
輸出是
集合的大小仍然是:2
因此,“區別性”將在這里出現。
如果使用C ++ 11進行編譯,則可以使用元組:
typedef tuple <int,int,int> my_type2;
typedef set<my_type2> set_of_tuples;
set_of_tuples myset2;
myset2.insert(make_tuple(1,3,4));
您的代碼會更容易:編寫make_tuple(1,3,4)比make_pair(1,make_pair(3,4))容易。 再加上元素訪問將更容易:
set_of_tuples::iterator it = my_set.find( make_tuple(1,3,4) )
my_type2 my_element = *it
cout << get<0>(my_element) << "," << get<1>(my_element) << "," get<2>(my_element) << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.