Ariel Baron Ariel Baron - 1 day ago 6
C++ Question

Picking all elements of a vector that don't equal a value

Say I have a std:: vector of size 12.
I want to pick 6 elements of the vector that don't equal 2 or 30.
How would I do this?

I have tried:

for (int i=0; i<12; i++)
{ if (vector.at(i) != 2 && vector.at(i) != 30)
{ selected_number = vector.at(i);
// do stuff

}
else
{ selected_number=vector.at(i+1)
// ?? I am confused about what to do here.
// how do I get vector.at(i) to equal something other than 2 or 30?

}




}

Answer

So you want the first 6 elements of vector foo which aren't 2 or 30?

How about

std::vector<int> bar;
for(auto i : foo){
  if(i != 2 && i != 30 && bar.size() < 6) {
    bar.emplace_back(i);
  }
}

That's not perfect but it's one of the simpler ways to skin this particular cat.

Comments