vector question

P

Pat

Hi,

I use vector<int> to store a list of numbers. Give any number X (may not be
in the vector), I am looking for an efficient way to delete all X's in the
vector.

Any suggestion?
Thanks. Pat
 
J

John Harrison

Pat said:
Hi,

I use vector<int> to store a list of numbers. Give any number X (may not be
in the vector), I am looking for an efficient way to delete all X's in the
vector.

Any suggestion?
Thanks. Pat

#include <algorithm>
#include <vector>

vec.erase(std::remove(vec.begin(), vec.end(), val), vec.end());

john
 
S

Sumit Rajan

Pat said:
Hi,

I use vector<int> to store a list of numbers. Give any number X (may not be
in the vector), I am looking for an efficient way to delete all X's in the
vector.

Any suggestion?

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{


std::vector<int> v;
for (int i=0; i<10;i++)
v.push_back(i);
v.push_back(3);
v.push_back(4);

std::copy(v.begin(),v.end(),
std::eek:stream_iterator<int>(std::cout, " "));
std::cout << '\n';

v.erase(std::remove(v.begin(),v.end(),3),v.end()); //in vector
v.erase(std::remove(v.begin(),v.end(),45),v.end()); //not in vector

std::copy(v.begin(),v.end(),
std::eek:stream_iterator<int>(std::cout, " "));
std::cout << '\n';
}

Regards,
Sumit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top