如何从集合C 显示某个项目
How to display a certain item from the set C++
我有一个集合,假设set<string>tmpSet
。我有一些元素,例如10
,但我不知道它们是什么,因为我得到了另外两个集合的set_intersection
集。我可以显示集合中的first, third and eighth
元素吗?
是。
std::set<std::string> tmpSet = ...; // Create your set somehow.
// Get an iterator to the first (smallest) item in the set.
std::set<std::string>::iterator setStartIt = tmpSet.begin();
// Dereference the iterator to obtain a reference to the first element.
std::string& firstItem = *setStart;
// Get an iterator for the third element (this is two after the first!).
auto thirdItemIt = std::next(setStartIt, 2);
std::string& thirdItem = *thirdItemIt;
// Get the tenth item.
std::string& tenthItem = *std::next(setStartIt, 9);
请注意,您还可以使用std::advance()
(它可以修改您通过的迭代器而不是返回新的迭代器。还要记住这不是有效的:由于std::set
迭代器不是RandomAccessIterator
,因此std::next
和std::advance
的复杂性是线性的(因此需要10个操作才能获取第10个项目(。
如果您想查看所有元素,那么对它们进行循环,这当然是正确的方法:
for (auto it = tmpSet.begin(); it != tempSet.end(); ++it) {
std::string currentElement = *it;
...
}
或使用基于范围的循环:
for (auto& currentElement : tmpSet)
...
std::set
中的元素始终是>(通常以 red-black tree
实现的设置(。当然可以使用有趣的属性。
通过使用range-based for
(自CPP11(或搜索set::begin()
和set::end()
之间的部分,您可以为内部的元素提供确保。
这是参考http://en.cppreference.com/w/cpp/container/set
可以在此处找到STD ::的描述。要点是
- 元素被排序
- 元素是唯一的
- 查找时间为o(lg2(n((
- 插入时间也为o(lg2(n((
- 元素访问双向。您可以迭代前进和向后,但是不能像
tmpSet[8]
那样选择一个随机元素。这意味着o(n(随机元素的访问时间。
如果您确实想随机访问,则可以使用boost :: flat_set。除
以外,这具有与上述相同的属性- 插入时间为o(n(
- 元素访问是随机的,因此您可以编写
tmpSet[8]
,哪些具有O(1(复杂性。
相关文章:
- 当我在libtorrent上调用dht_get_item时,警报显示该项目未初始化
- Xcode Test Navigator 如何在纯C++项目中显示 Google 测试
- qtableView 在订购项目到达时添加和显示它们任意?
- 创建直方图以显示每个类别/箱中带有星号的项目数量
- 双向链表问题 - 包含项目但不显示
- 如何在QListWidget中显示QStringList的每个项目QLabel和另一个QString?
- 在选定的 QMenu 项目上显示刻度图像
- Directx11 项目将不显示图形输出
- 如何从集合C 显示某个项目
- 如何在矢量中显示特定项目<char>?(C++)
- C++:读入文件并显示单个项目
- QML地图:大量显示的项目
- C++/CLI 项目如何在控制台窗口中显示消息
- Visual C CLR设计器在项目的第二次运行和编辑设计中始终显示0x8000000A错误
- 如何在 Xcode 项目导航器中显示.txt文件
- 从VS2008升级后,VS2012中的构建项目显示错误
- Eclipse 在我安装 CDT 后没有显示任何C++项目选择
- EclipseCDT显示了一些错误,但该项目已成功构建
- CMFCToolBar 和 CMFCMenuBar 默认不显示动态项目
- 默认项目显示在不可编辑的组合框中