开发者

Erasing a vector element by key

ive defined the following and filled it with elements:

vector <vector<double> > my_vector;

but i want a delete an elem开发者_运维百科ent with a specific key...

my_vector.erase(int(specific_key));

but it doesnt allow me. how would i properly dispose of the elements assigned to that key properly?


Assuming by specific_key you mean the element at that position in the vector:

my_vector.erase(my_vector.begin() + specific_key);

Would be the "most correct" answer.

If you meant to delete the element that matches specific_key (which will have to be of type vector<double> in the given example:

my_vector.erase(find(my_vector.begin(), my_vector.end(), specific_key));


erase takes in an iterator as argument.

You can do

my_vector.erase (my_vector.begin() + specific_key);

You can also pass in a range

my_vector.erase (my_vector.begin(), my_vector.begin() + 2);

One thing that you should note is that the size of the vector also gets reduced.


The erase method takes iterators as their argument.

Example


If Specific key is not position and say its some data in vector, then one has to iterate vector for that data and erase particular iterator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜