想象一下我有一个结构
struct Square{
int width;
int height;
};
然后我在代码中的某个地方有一个功能
void create_vec_squares(std::vector<Square> &dest){
for(int i = 0; i < 10; i++){
//create squares and put then into the destination vector
}
}
在C ++中使用什么是正确的方法?我知道一些C,我的想法是使用内存分配技术,如malloc。但是,我需要输入一个void delete_vec_squares(...)以确保正确释放内存。
我想知道这种方法是否会出现任何问题
void create_vec_squares(std::vector<Square> &dest){
for(int i = 0; i < 10; i++){
int val1,val2;
//generate some values for squares
...
//end generation
dest.push_back({val1, val2});
}
}
根据我的理解,不是在堆上分配内存,而是将结构简单地推送到堆栈上,并且不需要手动内存分配技术;
答案 0 :(得分:1)
而不是在堆上分配内存,结构将被简单地推送到堆栈上,并且不需要手动内存分配技术;
你是对的。当你 push_back 时,你只需要 push_back ,因为
std::vector<T>::push_back(const T & val);
基于副本。
您的Square
对象将安全地保存在std::vector<Square>
范围之外。
如果您在Square
中进行了一些分配,那么它的Square::~Square()
工作就可以解除所需的工作。
答案 1 :(得分:0)
push_back
是一个向量方法,它在向量的末尾添加一个新元素,在其当前的最后一个元素之后。
您可以执行以下操作:
void create_vec_squares(std::vector<Square> &dest){
for(int i = 0; i < 10; i++){
//create an object Square and lets call it newSquare, then you can use push_back
dest.push_back(newSquare);
//this will add your object newSquare at the end of vector dest
}
}
如果你想完全清空矢量,可以使用dest.clear()
。通过使用包含的方法,它可以减少对象vector
管理不善的可能性,并且通常更安全。
答案 2 :(得分:0)
我想知道这种方法是否会出现任何问题
void create_vec_squares(std::vector<Square> &dest){
for(int i = 0; i < 10; i++){
int val1,val2;
//generate some values for squares
...
//end generation
dest.push_back({val1, val2});
}
}
此方法的唯一问题是您的代码可能无法移植。有些地方仍然坚持使用C ++ 03编译器,它没有统一的初始化。
关于适当的方法,没有一种适当的方法。当您可以使用它时,统一初始化很棒。你不能总是使用它(即使在C ++ 11及更高版本中)。有时您需要使用显式构造函数,有时您需要在将项目添加到容器之前对其进行操作。仍然不需要new
和delete
。只需声明一个局部变量并将其推回容器即可。
当你知道要将一大堆物体放到矢量上时,为进入的船载预留一些空间可能是有利的。你的代码有一个boatload(10000)对象而不是10:
void create_vec_squares(std::vector<Square> &dest){
dest.reserve(dest.size() + 10000);
for(int i = 0; i < 10000; i++){
int val1,val2;
//generate some values for squares
...
//end generation
dest.push_back({val1, val2});
}
}
答案 3 :(得分:0)
如果您确切知道要在dest
中设置十个对象,则以下方法可能更清晰,更快:
struct Square{
int width;
int height;
Square & set(int p_width, int p_height) {
width = p_width; height = p_height;
return (*this);
}
};
typedef std::vector<Square> Square_vec;
void create_vec_squares(Square_vec & dest){
//create squares
dest.reasize(10);
for(Square_vec::iterator v_i = dest.begin(), v_e = dest.end(); v_i < v_e; ++v_i){
// and put then into the destination vector
v_i->set(val1, val2); //The already created Square object is set whithout temporary.
//Or if you have common temporay Square object:
*v_i = tmpSquare;
}
}
重构的下一步可能是创建一个仿函数,用于填充从for_each
而不是<algorithm>
循环替换为for(Square_vec::iterator ...
函数的Square_vec。