2010-03-29 36 views
12

有了一個載體,我可以做到以下幾點:訪問集合中的元素?

vector<int> myvec (4,100); 
int first = myvec.at(0); 

我有以下設置:

set<int> myset; 
myset.insert(100); 
int setint = ???? 

我如何訪問我在集合插入的元素?

+1

哪些元素?爲了什麼目的? – GManNickG 2010-03-29 20:23:10

回答

13
set<int>::iterator iter = myset.find(100); 
if (iter != myset.end()) 
{ 
    int setint = *iter; 
} 
+1

在取消引用該迭代器之前,您應該檢查'iter!= myset.end()'。 – 2010-03-29 20:19:10

+3

如果你知道你在尋找100,爲什麼不把100賦給'setint'? – wilhelmtell 2010-03-29 20:19:30

+0

與'vector'情況下的等價物是'vecint = * find(myvec.begin(),myvec.end(),100);' – wilhelmtell 2010-03-29 20:21:13

7

您無法按索引訪問設置的元素。您必須使用迭代器訪問元素。

set<int> myset; 
myset.insert(100); 
int setint = *myset.begin(); 

如果您想要的元素不是第一個元素,則將迭代器推進到該元素。您可以使用set<>::find()查看集合以查看元素是否存在,或者您可以迭代該集合以查看存在哪些元素。

+0

只有當你從組。 – UncleBens 2010-03-29 20:39:23

+0

啊,對不起。插入一個集合不會使舊的迭代器無效,並且擦除元素也不會使舊的迭代器無效(當然除了指向元素的迭代器被刪除)。 – wilhelmtell 2010-03-29 20:51:47

1

您也可以使用這種方法:

set<int>:: iterator it; 
for(it = s.begin(); it!=s.end(); ++it){ 
    int ans = *it; 
    cout << ans << endl; 
}