Search a list: Difference between revisions
Content added Content deleted
Alextretyak (talk | contribs) (Added 11l) |
m (code cleanup) |
||
Line 717: | Line 717: | ||
*/ |
*/ |
||
#include <iostream> // std::cout |
#include <iostream> // std::cout |
||
#include <algorithm> // std::find |
#include <algorithm> // std::find |
||
#include <list> // std::list |
#include <list> // std::list |
||
Line 740: | Line 740: | ||
// lambda function with auto typing |
// lambda function with auto typing |
||
// auto is easier to write than looking up the |
// auto is easier to write than looking up the complicated |
||
// specialized iterator type that is actually returned. |
// specialized iterator type that is actually returned. |
||
// Just know that it returns an iterator for the list at the position found, |
// Just know that it returns an iterator for the list at the position found, |
||
Line 748: | Line 748: | ||
auto contains = [](list<string> l, string s) throw(runtime_error) |
auto contains = [](list<string> l, string s) throw(runtime_error) |
||
{ |
{ |
||
auto r = find(begin(l), end(l), s ); |
auto r = find(begin(l), end(l), s ); |
||
if |
if( r == end(l) ) |
||
throw runtime_error( s + " not found" ); |
|||
return r; |
return r; |
||
}; |
}; |
||
Line 761: | Line 762: | ||
// name to simplify things. |
// name to simplify things. |
||
auto index = [&](list<string> l, string s) noexcept |
auto index = [&](list<string> l, string s) noexcept |
||
{ |
{ |
||
vector<int> index_v; |
vector<int> index_v; |
||
Line 767: | Line 768: | ||
int idx = 0; |
int idx = 0; |
||
for( |
for(const string& r : l) |
||
{ |
{ |
||
if |
if( s.compare(r) == 0 ) // match -- add to vector |
||
index_v.push_back(idx); |
|||
⚫ | |||
⚫ | |||
} |
} |
||
Line 782: | Line 785: | ||
// for |
// range-based for loop |
||
// s is a read-only reference, not a copy |
|||
for (const string& s : n) // new iteration syntax is simple and intuitive |
for (const string& s : n) // new iteration syntax is simple and intuitive |
||
{ |
{ |
||
Line 790: | Line 794: | ||
auto cont = contains( l , s); // checks if there is any match |
auto cont = contains( l , s); // checks if there is any match |
||
if( cont != l.end() ) // found at least one |
|||
⚫ | |||
{ |
|||
⚫ | |||
cout << "l contains: " << s << " at " ; |
cout << "l contains: " << s << " at " ; |
||
for(auto x : vf) // auto will resolve to int |
|||
{ cout << x << " "; } // if vector is empty this doesn't run |
{ cout << x << " "; } // if vector is empty this doesn't run |
||
cout << |
cout << "\n"; |
||
} |
|||
} |
} |
||
catch (const runtime_error& r) // string not found |
catch (const runtime_error& r) // string not found |
||
{ |
{ |
||
cout << r.what() << |
cout << r.what() << "\n"; |
||
continue; // try next string |
continue; // try next string |
||
} |
} |
||
} //for |
} //for |
||