Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Random question

Name: Anonymous 2009-11-25 21:52

Using c++, I have a string vector containing thousands of elements. I know I can erase a specific element using:

vectorName.erase(remove(vectorName.begin(),vectorName.end(),"whatever"),vectorName.end());

In that example it would get rid of any vector elements that equaled "whatever".

I'm looking to erase certain elements if anywhere in that element it has a certain combination of letters. In my case, I want to erase any URLs that make it into the vector, so I would erase any element that contained "http" or "www" in it.

I tried googling this, but I have no clue what to look for. Can anyone offer their expertise? Is there a one line solution using vectorName.erase()?

Name: Anonymous 2009-11-26 2:02

>>3
You're not Thinking in Sepples yet.

#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>

using namespace std;

// If either of the arguments is a reference it can't be used with ptr_fun/bind2nd
// because the workings of binder2nd would form a reference to a reference, which is
// illegal.
bool contains(string s, string t) {
    return s.find(t) != string::npos;
}

template<class A, class B, class Arg>
struct unary_or_function: unary_function<Arg, bool> {
    unary_or_function(A const& f, B const& g)
        : f(f), g(g) { }

    bool operator() (Arg x) const {
        return f(x) || g(x);
    }

    const A& f;
    const B& g;
};

template<class A, class B>
unary_or_function<A, B, typename A::argument_type>
unary_or(A const& f, B const& g) {
    return unary_or_function<A, B, typename A::argument_type> (f, g);
}

int main() {
    vector<string> strings;
    strings.push_back("one");
    strings.push_back("two");
    strings.push_back("three");
    strings.push_back("http://four");
    strings.push_back("www.opera.com");
    strings.push_back("six");
   
    copy(strings.begin(), strings.end(), std::ostream_iterator<string>(cout, "\n"));

    vector<string>::const_iterator new_end =
        std::remove_if(strings.begin(), strings.end(), unary_or(
            bind2nd(ptr_fun(contains), "http"),
            bind2nd(ptr_fun(contains), "www")));
    strings.erase(new_end, strings.end());

    copy(strings.begin(), strings.end(), std::ostream_iterator<string>(cout, "\n"));
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List