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.
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.
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.
Elements can be added in the middle of a Vector by using the java. util. Vector. insertElementAt() method.
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; });
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