1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
class Person
{
std::string first;
std::string st;
public:
Person() { }
Person(const std::string& arg_first, const std::string& arg_st) :
first(arg_first), st(arg_st) { }
std::string first_name() const { return first; }
std::string state() const { return st; }
};
struct Person_from_texas1
{
bool operator()(const Person& a)
{
if(a.state() == "Texas") { return true; }
else { return false; }
}
};
int main()
{
std::vector<Person> v;
v.push_back(Person("Peter", "Texas"));
v.push_back(Person("Bill", "Texas"));
v.push_back(Person("Herbert", "Texas"));
v.push_back(Person("John", "Ohio"));
auto Person_from_texas2 = [](const Person& a)
{
if(a.state() == "Texas") { return true; }
else { return false; }
};
std::vector<Person> v_texas;
/*Try the first one, the isolate it with a comment and try the second one*/
std::copy_if(v.cbegin(), v.cend(), std::back_inserter(v_texas), Person_from_texas1());
//std::copy_if(v.cbegin(), v.cend(), std::back_inserter(v_texas), Person_from_texas2);
// should be range-based for-loop, but if you haven't seen one, it might confuse you at first.
for(int i = 0; i < v_texas.size(); ++i)
{
std::cout << v_texas[i].first_name() << '\t' << v_texas[i].state() << '\n';
}
return 0;
}
|