C++ 访问集合中的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2540950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:51:37  来源:igfitidea点击:

Access an element in a set?

c++set

提问by mr.bio

With a vector, I can do the following:

使用向量,我可以执行以下操作:

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

I have the following set:

我有以下设置:

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

How can I access the the element I inserted in the set?

如何访问我插入到集合中的元素?

采纳答案by Michael Kristofik

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

回答by wilhelmtell

You can't access set elements by index. You have to access the elements using an iterator.

您不能通过索引访问集合元素。您必须使用迭代器访问元素。

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

If the element you want is not the first one then advance the iterator to that element. You can look in a set to see if an element exists, using set<>::find(), or you can iterate over the set to see what elements are there.

如果您想要的元素不是第一个元素,则将迭代器推进到该元素。您可以查看集合以查看元素是否存在,使用set<>::find(),或者您可以遍历集合以查看存在哪些元素。

回答by Rafsan

You can also use this approach :

您也可以使用这种方法:

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