I’m looking for a way to find the longest word ( base on length ) in a text document using STL and boost.
Here is my solution. However, it wasn’t good at all, there were too many operations( token, sort .. ). Is there any simpler way to solve this problem?
// utility and memory
#include <utility>
#include <functional>
#include <memory>
#include <locale>
#include <string>
// data structure and algorithm
#include <stack>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <deque>
#include <list>
#include <bitset>
#include <algorithm>
#include <iterator>
// numeric
#include <complex>
#include <numeric>
#include <valarray>
// input/output
#include <iostream>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <streambuf>
#include <sstream>
// standard C
#include <cctype>
#include <cmath>
#include <climits>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <cstring>
// boost
#include <boost/tokenizer.hpp>
int main() {
std::string str = "Test, test!, test...string";
boost::char_separator<char> sep( ",!,.-" );
boost::tokenizer<boost::char_separator<char> > tokens( str, sep );
std::vector<std::string> res;
std::copy( tokens.begin(), tokens.end(), std::back_inserter( res ) );
std::sort( res.begin(), res.end(), []( const std::string& l, const std::string& r ) { return l.length() > r.length(); } );
std::cout << "longest : " << *res.begin() << "\n";
return 0;
}
Best regards,
Chan
You can use
std::max_element. Just give to it iterator pair and the comparator which you’ve already written.