简体   繁体   中英

Delete Row in 2D Vector C++

So I have the example vector initialized as so:

vector<vector<int> > v = {{1, 2, 3},{4, 5, 6},{7, 8, 9}}

I want to totally delete the row, {4, 5, 6} such that v[1][0] references 7 and the final vector is v = {{1, 2, 3},{7, 8, 9}}

v[1].clear() does not accomplish this, and v[1].erase(v[1].begin(),v[1].begin()+3) doesnt seem to either unless I am just an idiot.

Thank you in advance!

You should erase whole nested vector, not just items inside.

If you writing v[1].erase(v[1].begin(),v[1].begin()+3) , you got {{1,2,3},{},{7,8,9}} . Just write what Albin Paul said: v.erase(v.begin() + 1) and then your vector will be v = {{1,2,3},{7,8,9}} .

Adding onto Vslav, if the vector you want to delete is conveniently at the end of your 2d matrix, then just do v.popback(). It is simpler but only works on the final element. You could also do some research on remove() function.

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