简体   繁体   中英

Can I use the insert function to add elements into a vector of vectors?

I would like to know, can I use insert keyword to add elements into vector of vector ?
For example, I have a vector vector<int> temp1; for this vector , elements add within the inner for loop. at the end of out for loop, I need to add the elements to temp1 ;

vector<vector<int> >temp1;
for (int a;a<size(),a++){//...
  vector<int> temp2;
  for (int b=0;b<closer_points;b++){

       // some steps here...

       vector<int> pt_no=mydata.Find_End_point(my_list,s1,s2);
       temp2=pt_no;
       }
  temp1[a].insert(temp1[a].end(),temp2.begin(),temp2.end());
  }

then, i tried to print temp1 , line by line as elements of temp2 are appearing in a one line.

for(int i=0;i<temp1.size();i++){
    for(int j=0;j<temp1[i].size();j++){
        cout<<" t2 "<<temp1[i][j];
        }
    cout<<endl;
    }

but, this doesnt work. can anyone rectify this, plz...

您需要使用temp1.push_back(temp2);

Question:

temp1[a].insert(temp1[a].end(),temp2.begin(),temp2.end());

Reinstated prior answer:

To append a range of values to an existing vector:

std::copy(temp2.begin(),temp2.end(), std::back_inserter(temp1));

To append the range as a new vector to an existing vector_of_vectors:

vector<vector<int> > vecvec;
vector<int> toappend;

// some steps :)
vecvec.push_back(toappend);

// or
vecvec.push_back(vector<int>(toappend.begin(), toappend.end());

include <iterator> and <algorithm> if you haven't got them already

Update

if i say like this; i have set of points. i want to group these points into vectors and then to put those into another vector at the end. so, i gues my final output is vector of vector. for example, final result should look like ((1,3),(4,6,9,8,21),(5,7,12),..).

Ok, here goes:

// (
std::vector<std::vector<int> > vecvec;
// (1,3)
{
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(3);

    vecvec.push_back(vec);
}
// (4,6,9,8,21)
{
    std::vector<int> vec;
    vec.push_back(4);
    vec.push_back(6);
    vec.push_back(9);
    vec.push_back(8);
    vec.push_back(21);

    vecvec.push_back(vec);
}
// (5,7,12)
{
    std::vector<int> vec;
    vec.push_back(5);
    vec.push_back(7);
    vec.push_back(12);

    vecvec.push_back(vec);
}
// )
//  ....
... // (use vecvec)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM