Problem: I have a class CPerson whose member variables are Age and Marks. I have created a vector of persons and populated with the objects. Now i want t开发者_StackOverflowo extract only the persons who have scored 100 marks.
My Approach: I tried to sort the vector based on marks and then looped through the vector to find the first position of 100 and then again looped until the marks are different. The problem here is i need to do it manually. Tommorow if i want to search by Age then i need to repeat the same algorithm. Is there any other way to do it?
can i use partial_sort_copy or upper_bound/lower_bound functions to achieve it.
I am using VS2008
It sounds like you need the remove_copy_if
function, which could be better named as copy_if_not
. Unfortunately, the copy_if
function is missing from STL.
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
typedef int CPerson;
bool HasNotScoredHundred(const CPerson & person)
{
return person < 100;
}
void Print(const CPerson & person)
{
cout << person << " ";
}
int main()
{
vector<CPerson> people;
people.push_back(CPerson(50));
people.push_back(CPerson(150));
people.push_back(CPerson(100));
people.push_back(CPerson(0));
vector<CPerson> elite;
remove_copy_if
( people.begin()
, people.end()
, back_inserter(elite)
, HasNotScoredHundred
);
for_each(people.begin(), people.end(), Print);
cout << "\n";
for_each(elite.begin(), elite.end(), Print);
}
Output:
50 150 100 0
150 100
Of course, if you wanted to adjust the mark threshold, you would use a functor instead of the HasNotScoredHundred
function.
精彩评论