Wednesday, April 1, 2009

c++ stl - use find_if for finding all items of set that contains satin substring

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <iostream>
#include <set>
#include <functional>
#include <iterator>

struct checkIfContainsSubstr: 
public std::binary_function<std::string, std::string, bool>
{
    bool operator()(const std::string& str1, 
                    const std::string& str2) const 
    {
        return ((str1.find(str2) == std::string::npos)?(false):(true));
    }
};

int main(int argc, char** argv)
{
    std::set<std::string> testSet;

    testSet.insert("111test111");
    testSet.insert("test333");
    testSet.insert("111111");
    testSet.insert("222222");
    testSet.insert("2test222");
    testSet.insert("3test222");

    std::copy(testSet.begin(), testSet.end(),
            std::ostream_iterator<std::string>(std::cout, " "));
    std::cout << std::endl;            

    std::set<std::string>::iterator it = testSet.begin();
    while(it != testSet.end())
    {
        it = std::find_if(it, testSet.end(),
                            std::bind2nd(checkIfContainsSubstr(), "test"));
        if (it != testSet.end())
        {
            std::cout << "Found substr: " << (*it) << std::endl;
            it++;
        }
    }

    return 0;
}