Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make std::vector from other vector with specific filter?

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.

like image 222
Protheus Avatar asked Jun 14 '12 07:06

Protheus


People also ask

How do you create a vector from another vector in C++?

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.

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 you move a value from one vector to another?

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.

How do you create a vector of a certain size?

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));


2 Answers

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.

like image 177
juanchopanza Avatar answered Oct 08 '22 00:10

juanchopanza


you can use the std::copy_if method. See here.

like image 37
Eugen Avatar answered Oct 08 '22 00:10

Eugen