Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do C++ professional programmers implement common abstractions?

I've never programmed with C++ professionally and working with (Visual) C++ as student. I'm having difficulty dealing with the lack of abstractions especially with the STL container classes. For example, the vector class doesn't contain a simple remove method, common in many libraries e.g. .NET Framework. I know there's an erase method, it doesn't make the remove method abstract enough to reduce the operation to a one-line method call. For example, if I have a

std::vector<std::string>

I don't know how else to remove a string element from the vector without iterating thru it and searching for a matching string element.

bool remove(vector<string> & msgs, string toRemove) {
if (msgs.size() > 0) {
    vector<string>::iterator it = msgs.end() - 1;   
    while (it >= msgs.begin()) {
        string remove = it->data();
        if (remove == toRemove) {
            //std::cout << "removing '" << it->data() << "'\n";
            msgs.erase(it);
            return true;
        }
        it--;
    }
}   
return false;

}

What do professional C++ programmers do in this situation? Do you write out the implementation every time? Do you create your own container class, your own library of helper functions, or do you suggest using another library i.e. Boost (even if you program Windows in Visual Studio)? or something else?

(if the above remove operation needs work, please leave an alternative method of doing this, thanks.)

like image 525
T. Webster Avatar asked Jul 03 '11 20:07

T. Webster


1 Answers

You would use the "remove and erase idiom":

v.erase(std::remove(v.begin(), v.end(), mystring), v.end());

The point is that vector is a sequence container and not geared towards manipulation by value. Depending on your design needs, a different standard library container may be more appropriate.

Note that the remove algorithm merely reorders elements of the range, it does not erase anything from the container. That's because iterators don't carry information about their container with them, and this is fully intentional: By separating iterators from their containers, one can write generic algorithms that work on any sensible container.

Idiomatic modern C++ would try to follow that pattern whenever applicable: Expose your data through iterators and use generic algorithms to manipulate it.

like image 190
Kerrek SB Avatar answered Sep 22 '22 21:09

Kerrek SB