vector的类型是结构时,初始化问题

@浪里小白龙 2018-10-23 12:36:29

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

struct node
{
int come, times;
}tempcustomer;

bool cmp(node a, node b) { //升序排
return a.come<b.come;
}

int main()
{
int n, k;
scanf_s("%d%d", &n, &k);
vector<node> custom;
for (int i = 0; i<n; i++) {
int hh, mm, ss, p;
scanf_s("%d:%d:%d %d", &hh, &mm, &ss, &p);
int cometime = hh * 3600 + mm * 60 + ss;
if (cometime>61200) continue;
tempcustomer = { cometime,p * 60 };
custom.push_back(tempcustomer);
}
sort(custom.begin(), custom.end(), cmp);
vector<int> window(k, 28800);
double result = 0.0;

for (int i = 0; i<custom.size(); i++) {
int tempindex = 0, minfinish = window[0];
for (int j = 1; j<k; j++) {
if (minfinish>window[j]) {
minfinish = window[j];
tempindex = j;
}
}
if (window[tempindex] <= custom[i].come) {
window[tempindex] = custom[i].come + custom[i].times;
}
else {
result += (window[tempindex] - custom[i].come);
window[tempindex] += custom[i].times;
}
}
if (custom.size() == 0) {
printf("0.0");
}
else {
printf("%.1f", result / 60.0 / custom.size());
}

return 0;
}

测试用例
7 3
07:55:00 16
17:00:01 2
07:59:59 15
08:01:00 60
08:00:00 30
08:00:02 2
08:03:00 10
这是我的代码,如果将19行的vector<node> custom;写为vector<node> custom(n); 也就是初始化一下,结果就不正确了,是因为什么呀。
...全文
164 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
@风轻云淡_ 2018-10-23
  • 打赏
  • 举报
回复
凡是定义的时候带括号来初始化的,都是利用他的构造函数来的。vector<node> custom(n);是指定他的长度并不是初始化它,想要初始化它可以用memset函数,也可以用vector<node> custom = {{1,2}};
@浪里小白龙 2018-10-23
  • 打赏
  • 举报
回复
引用 1 楼 sinat_37764097 的回复:
push_back 在尾部插入,初始化为7后,容器的长度就是7了,然后你再来个push_back,长度实际上已经是8了。
谢谢大佬。我命变了
@浪里小白龙 2018-10-23
  • 打赏
  • 举报
回复
哇,我明白了。谢谢大佬。
云山大侠 2018-10-23
  • 打赏
  • 举报
回复
push_back 在尾部插入,初始化为7后,容器的长度就是7了,然后你再来个push_back,长度实际上已经是8了。

64,649

社区成员

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

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