How to use vector::push_back()` with a struct?(如何将 vector::push_back()` 与结构一起使用?)
问题描述
如何将 push_back struct 转化为向量?
How can I push_back a struct into a vector?
struct point {
int x;
int y;
};
std::vector<point> a;
a.push_back( ??? );
推荐答案
point mypoint = {0, 1};
a.push_back(mypoint);
或者如果你被允许,给 point 一个构造函数,这样你就可以使用一个临时的:
Or if you're allowed, give point a constructor, so that you can use a temporary:
a.push_back(point(0,1));
如果你在一个用struct声明的类中放置一个构造函数,有些人会反对,这使它成为非POD,也许你无法控制point的定义代码>.因此,您可能无法使用此选项.但是,您可以编写一个提供相同便利的函数:
Some people will object if you put a constructor in a class declared with struct, and it makes it non-POD, and maybe you aren't in control of the definition of point. So this option might not be available to you. However, you can write a function which provides the same convenience:
point make_point(int x, int y) {
point mypoint = {x, y};
return mypoint;
}
a.push_back(make_point(0, 1));
这篇关于如何将 vector::push_back()` 与结构一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 vector::push_back()` 与结构一起使用?
基础教程推荐
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
