如何从集合C 显示某个项目

How to display a certain item from the set C++

本文关键字:项目 显示 集合      更新时间:2023-10-16

我有一个集合,假设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::nextstd::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 ::的描述。要点是

  1. 元素被排序
  2. 元素是唯一的
  3. 查找时间为o(lg2(n((
  4. 插入时间也为o(lg2(n((
  5. 元素访问双向。您可以迭代前进和向后,但是不能像tmpSet[8]那样选择一个随机元素。这意味着o(n(随机元素的访问时间。

如果您确实想随机访问,则可以使用boost :: flat_set。除

以外,这具有与上述相同的属性
  1. 插入时间为o(n(
  2. 元素访问是随机的,因此您可以编写tmpSet[8],哪些具有O(1(复杂性。