Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific elements from a vector

Tags:

I have a vector v1, and a boolean vector v2 of the same size. I want to delete from v1 all values such that the parallel element of v2 is false:

vector<int> v3; // assume v1 is vector<int> for (size_t i=0; i<v1.size(); i++)     if (v2[i])         v3.push_back(v1[i]); v1=v3; 

Is there a better way to do it?

  • in C++03
  • in C++11
like image 849
user31264 Avatar asked Jul 14 '16 13:07

user31264


People also ask

How do you access a specific element in a vector?

Element access: reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.

How do I extract elements from a vector in R?

Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.

How do I remove a specific element from a vector position?

vector::erase() erase() function is used to remove elements from a container from the specified position or range.


1 Answers

size_t last = 0; for (size_t i = 0; i < v1.size(); i++) {   if (v2[i]) {     v1[last++] = v1[i];   } } v1.erase(v1.begin() + last, v1.end()); 

Same as yours essentially, except it works in-place, not requiring additional storage. This is basically a reimplementation of std::remove_if (which would be difficult to use directly, because the function object it uses is given a value, not an index or iterator into the container).

like image 108
Igor Tandetnik Avatar answered Oct 27 '22 15:10

Igor Tandetnik