c++结构体向量的适当方法

C++ Proper Methodology for vectors of structs

本文关键字:方法 结构体 向量 c++      更新时间:2023-10-16

假设我有一个struct

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});
    }
}

根据我的理解,不是在堆上分配内存,而是将结构简单地推到堆栈上,并且不需要手动内存分配技术;

不是在堆上分配内存,而是将结构简单地推到堆栈上,并且不需要手动内存分配技术;

你是对的。当你push_back时,你只需要push_back,因为

std::vector<T>::push_back(const T & val);

copy-based

您的Square对象将安全地保存在std::vector<Square>的作用域之外。

如果你在Square中做了一些分配,那么Square::~Square()的工作就是释放需要的东西。

push_back是一个vector方法,它在vector对象的最后一个元素后面添加一个新元素。

你可以这样做:

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对象管理不当的机会,并且通常更安全。

我想知道这个方法是否会出现问题

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和更高版本中)。有时需要使用显式构造函数,有时需要在将项添加到容器之前对其进行操作。仍然不需要newdelete。只需声明一个局部变量,并将其压回容器。


当您知道要将一船船的对象放到一个矢量上时,为即将到来的一船船保留一些空间可能是有利的。你的代码有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});
    }
}

如果您确切地知道要在dest中设置10个对象,那么下面的方法可能更简洁、更快:

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;
    }
}

重构的下一步可能是创建一个函子来填充从<algorithm>替换到for_each函数中的Square_vec,而不是for(Square_vec::iterator ...循环。