#include<iostream>
#include<vector>
using namespace std;
typedef struct {//声明一个结构体类型Date
int month;//日期中的月份
int day;//日期中的天
int year;//日期中的年份
}Date;
int main(){
std::vector<Date> stu;
stu.push_back({ .day=11 ,.year=8});
stu.push_back({.month=1});
return 0;
}
今天遇到一个问题,需要将一个结构体放进容器,然后在不同的函数里分别对结构体的其中某一项进行修改会出现以下错误:
non-trivial designated initializers not supported
vector只允许进行struct里的所有项一起进行修改而且不能更换顺序:
stu.push_back({ .month=1, .day=11 ,.year=8});
而不允许
stu.push_back({ .day=11 , .month=1, .year=8});
如果一定要分开来进行赋值该如何实现呢?先实例一个结构体,然后改结构体的内容,最后将结构体实例放进vector中。
#include<iostream>
#include<vector>
using namespace std;
typedef struct {//声明一个结构体类型Date
int month;//日期中的月份
int day;//日期中的天
int year;//日期中的年份
}Date;
int main(){
std::vector<Date> stu;
Date date;
date.day=1;
date.year=2;
stu.push_back(date);
return 0;
}