这段代码哪里错了?如何对set排序?

「已注销」 2018-08-15 03:57:10
#include<iostream>
#include<algorithm>
#include<set>
using namespace std;
int main()
{
set<int>s;
s.insert(1);s.insert(0);
sort(s.begin(),s.end());
return 0;
}
...全文
118 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2018-08-15
  • 打赏
  • 举报
回复
万一需要按照非sort内置的顺序排序捏?
  • 打赏
  • 举报
回复
不用排序,直接就是拍好了的:

#include<iostream>
#include<algorithm>
#include<set>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
srand(time(0)); // 设置随机数种子
set<int> s;
set<int>::iterator it;

s.insert(1);
s.insert(0);

for(int i=0; i < 100; i++)
{
s.insert(rand()%100); // 随机生成数字插入s当中
}

for(it = s.begin(); it != s.end(); it++) // 逐个输出元素
{
cout << *it << endl;
}

return 0;
}
sghcpt 2018-08-15
  • 打赏
  • 举报
回复
c++ std 98 中说明:
Internally, set containers keep all their elements sorted following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering.
所以楼主下面的代码就可以了,不需要调用sort函数吧:
#include<iostream>
#include<algorithm>
#include<set>
using namespace std;
int main()
{
set<int>s;
s.insert(1);s.insert(0);
return 0;
}
赵4老师 2018-08-15
  • 打赏
  • 举报
回复
转存到vector中后再sort

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧