向量的push_back向量

push_back vector of vector

本文关键字:向量 back push      更新时间:2023-10-16

我得到了一些向量的向量问题。在我的程序中,我为vector的vector定义了一个动态内存,并对元素进行了resize和pushback操作。

vector<vector<double> > *planes = new vector<vector<double> >
planes->resize(s_list->size()); // size of another vector that i need to use
vector<int>::iterator s_no;
for(s_no=s_list->begin(), int i=0; s_no!=s_list->end(); s_no++, i++){){
                        //where i i the indices of planes
     //some codes for computing length, width
     planes->at(i).push_back(lenght);
     planes->at(i).push_back(width);
}

它起作用了,我得到了我添加的所有值的打印。然后,我将新的矢量定义部分更改为

vector<vector<double> > *planes = 
              new vector<vector<double> >(s_list->size(),vector<double>(2,0.0))

并移除了调整大小的部分。然后,当我得到向量的输出时,我得到了所有的0值。你能纠正这个问题吗。

使用at而不是push_back

 planes->at(i).at(0)=lenght;
 planes->at(i).at(1)=width;

push_back()添加了新项目,因此在每个向量中以4个项目结束。您应该使用at()来修改现有的条目。

更好的方法是使用vector< pair<double,double> >,假设您总是有两个项目。