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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
std::list<std::string> beginWith( const std::string& prefix, const std::list<std::string>& seq );
std::list<std::string> endWith( const std::string& suffix, const std::list<std::string>& seq );
int main()
{
// http://www.stroustrup.com/C++11FAQ.html#init-list
const std::list<std::string> test_list { "Agreeable", "Doable", "Machine", "Makeable", "Available" };
const std::string suffix = "able";
const std::string prefix = "M";
{
// print test_list (range-based loop)
// http://www.stroustrup.com/C++11FAQ.html#for
// http://www.stroustrup.com/C++11FAQ.html#auto
for( const auto& str : test_list ) std::cout << str << ' ' ;
std::cout << '\n' ;
// print test_list (classical loop)
for( auto iter = test_list.begin() ; iter != test_list.end() ; ++iter ) std::cout << *iter << ' ' ;
std::cout << '\n' ;
}
{
std::cout << "\n\nprefixed with '" << prefix << "':\n........................\n" ;
// print list returned by beginWith (range-based loop)
for( const auto& str : beginWith( prefix, test_list ) ) std::cout << str << ' ' ;
std::cout << '\n' ;
// print list returned by beginWith (classical loop)
const auto bw_list = beginWith( prefix, test_list ) ; // we need a list object to iterate through
// note: begin() and end() are iterators to the same list
for( auto iter = bw_list.begin() ; iter != bw_list.end() ; ++iter ) std::cout << *iter << ' ' ;
std::cout << '\n' ;
}
{
std::cout << "\n\nsuffixed with '" << suffix << "':\n........................\n" ;
// print list returned by endWith (range-based loop)
for( const auto& str : endWith( suffix, test_list ) ) std::cout << str << ' ' ;
std::cout << '\n' ;
// print list returned by endWith (classical loop)
const auto ew_list = endWith( suffix, test_list ) ;
for( auto iter = ew_list.begin() ; iter != ew_list.end() ; ++iter ) std::cout << *iter << ' ' ;
std::cout << '\n' ;
}
}
std::list<std::string> beginWith( const std::string& prefix, const std::list<std::string>& seq )
{
std::list<std::string> result ;
// http://en.cppreference.com/w/cpp/string/basic_string/find (1)
for( const auto& str : seq ) if( str.find(prefix) == 0 ) result.push_back(str) ;
return result ;
}
bool has_suffix( const std::string& str, const std::string& suffix )
{ return str.size() >= suffix.size() && std::equal( suffix.rbegin(), suffix.rend(), str.rbegin() ) ; }
std::list<std::string> endWith( const std::string& suffix, const std::list<std::string>& seq )
{
std::list<std::string> result ;
// http://en.cppreference.com/w/cpp/algorithm/equal (1)
for( const auto& str : seq ) if( has_suffix( str, suffix ) ) result.push_back(str) ;
return result ;
}
|