You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何像vector一样通过索引访问set元素?求解决方法

问题解答

为什么*(myset.begin()+i)不可行?

std::set的迭代器是双向迭代器,这类迭代器仅支持++、--这类逐步移动的操作,不支持直接通过+i/-i进行随机偏移。而std::vector的迭代器是随机访问迭代器,才允许begin()+i这种直接跳转的操作,这就是你代码报错的核心原因。

解决办法

方法1:使用迭代器直接遍历(推荐,效率最高)

这是遍历set的标准方式,符合容器的设计逻辑:

#include <iostream>
#include <set>
using namespace std;

int main ()
{
  int myints[] = {75,23,65,42,13};
  std::set<int> myset (myints,myints+5);

  std::cout << "myset contains:";
  // 用迭代器遍历
  for (auto it = myset.begin(); it != myset.end(); ++it) {
      cout << " " << *it;
  }

  std::cout << '\n';
  return 0;
}

方法2:将set元素复制到vector后再索引访问

如果确实需要频繁通过索引访问元素,可以先把set的内容转存到vector(支持随机访问):

#include <iostream>
#include <set>
#include <vector>
using namespace std;

int main ()
{
  int myints[] = {75,23,65,42,13};
  std::set<int> myset (myints,myints+5);
  // 复制到vector
  vector<int> vec(myset.begin(), myset.end());

  std::cout << "myset contains:";
  for (int i = 0; i < vec.size(); i++) {
      cout << " " << vec[i];
  }

  std::cout << '\n';
  return 0;
}

方法3:用std::next实现索引式访问(不推荐,效率低)

std::next可以接受双向迭代器和偏移量,内部通过循环++来移动迭代器,但每次调用都会从头开始走i步,元素多的时候时间复杂度是O(n²),仅适合小数据量场景:

#include <iostream>
#include <set>
#include <iterator> // 需要包含这个头文件
using namespace std;

int main ()
{
  int myints[] = {75,23,65,42,13};
  std::set<int> myset (myints,myints+5);

  std::cout << "myset contains:";
  for (int i = 0; i < myset.size(); i++) {
      cout << " " << *next(myset.begin(), i);
  }

  std::cout << '\n';
  return 0;
}

内容的提问来源于stack exchange,提问作者Habibur Rahman Shihab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:55:15