Search a list: Difference between revisions

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