I have a std::vector
filled with objects. I want to filter and copy all the elements for which some predicate returns true
in to a new std::vector
.
I've looked at find
and search
functions but they only return iterators.
I'm using ObjC++ so I can use block functions as well as functors, if it helps. Can't use C++11 functions though.
The simplest way to create a vector from another vector is to use the assignment operator ( = ). vector<int> v2; v2 = v1; The code initializes a vector v2. Then we use the assignment operator to copy all elements of vector v1 to v2.
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.
You can't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector. If you want to change all the elements from the first vector into the second and vice versa you can use swap. @R.
To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));
If you have C++11 then use std::copy_if
as suggested in Eugen's answer. Otherwise, you can use std::remove_copy_if with appropriate modifications to your predicate's logic.
you can use the std::copy_if method. See here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With