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
|
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <iomanip>
struct customer
{
customer( int age, std::string name ) : age(age), name( std::move(name) ) {}
int age ; std::string name ;
friend std::ostream& operator<< ( std::ostream& stm, const customer& cust )
{ return stm << "customer{ " << cust.age << ", " << std::quoted(cust.name) << " }" ; }
};
int main()
{
std::vector< std::shared_ptr<customer> > seq
{
std::make_shared<customer>( 12, "abcd" ),
std::make_shared<customer>( 34, "efgh" ),
std::make_shared<customer>( 12, "ijkl" ),
std::shared_ptr<customer>{nullptr},
std::make_shared<customer>( 56, "mnop" ),
std::make_shared<customer>( 12, "qrst" ),
std::make_shared<customer>( 78, "uvwx" )
};
int age ;
std::cout << "age to be erased? " ;
std::cin >> age ; // enter 12
std::cout << "remove customers with age == " << age << '\n' ;
// capture age by value
const auto age_equals = [age] ( const auto& ptr ) { return ptr && ptr->age == age ; } ;
seq.erase( std::remove_if( std::begin(seq), std::end(seq), age_equals ), std::end(seq) ) ;
for( const auto& ptr : seq )
{
if(ptr) std::cout << *ptr.get() << " " ;
else std::cout << "<nullptr> " ;
}
std::cout << '\n' ;
}
|