Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I insert into a set, all the elements of a vector that matches a condition, in a single line of code

I have a vector of elements. I want to populate a set using the elements of this vector that match a certain condition. Can I do this using one line, or in any way that is more concise than the below?

// given vector<int> v

set<int> s;
for (const int& i : v)
{
    if (/* some condition on i*/)
        s.insert(i);
}

For example, something along the line of:

// given vector<int> v

set<int> s;
s.insert(v.filter(/* lambda here*/));

It goes without saying that the v.filter method should return an iterator, not a separate populated vector, for performance reasons.

like image 249
nappyfalcon Avatar asked Apr 11 '18 14:04

nappyfalcon


People also ask

How do you check if all elements are same in a vector?

Method 2: Using length() and unique() function By using unique function if all the elements are the same then the length is 1 so by this way if the length is 1, we can say all elements in a vector are equal.

What is the algorithm complexity for inserting into a vector?

Its time complexity is O(1). insert(): Inserts new elements into the vector at a particular position. ts time complexity is O(N + M) where N is the number of elements inserted and M is the number of the elements moved . pop_back(): Removes the last element from the vector.

Can we add an element in the middle in vector?

Elements can be added in the middle of a Vector by using the java. util. Vector. insertElementAt() method.


1 Answers

You can use std::copy_if with a lambda and std::inserter to insert the values into the set. That looks like

std::copy_if(v.begin(), v.end(), std::inserter(s, s.begin()), [](auto val) { return val == some_condition; });
like image 78
NathanOliver Avatar answered Nov 02 '22 11:11

NathanOliver