Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the STL algorithms be used instead of using your own?

Tags:

c++

algorithm

stl

I frequently use the STL containers but have never used the STL algorithms that are to be used with the STL containers.

One benefit of using the STL algorithms is that they provide a method for removing loops so that code logic complexity is reduced. There are other benefits that I won't list here.

I have never seen C++ code that uses the STL algorithms. From sample code within web page articles to open source projects, I haven't seen their use.

Are they used more frequently than it seems?

like image 899
zooropa Avatar asked Jul 06 '10 17:07

zooropa


People also ask

Why should we use STL?

The STL exemplifies generic programming rather than object-oriented programming, and derives its power and flexibility from the use of templates, rather than inheritance and polymorphism. It also avoids new and delete for memory management in favor of allocators for storage allocation and deallocation.

Should you use STL?

You should use STL, because it is well tested and optimized. That doesn't mean you shouldn't know how to write these data structures yourself. With that ability under your belt, you will be able to choose the best STL data structure for your application.

How are STL algorithms different from conventional algorithms?

How STL algorithms are different from the conventional algorithms? Algorithms are functions that can be used generally across a variety of containers for processing their contents. Conventional algorithms are very lengthy and complex, where STL algorithms are very easy and short that can save a lot of time and effort.

What is STL algorithm?

The Standard Template Library, or STL, is a C++ library of container classes, algorithms, and iterators; it provides many of the basic algorithms and data structures of computer science. The STL is a generic library, meaning that its components are heavily parameterized: almost every component in the STL is a template.


1 Answers

Short answer: Always.

Long answer: Always. That's what they are there for. They're optimized for use with STL containers, and they're faster, clearer, and more idiomatic than anything you can write yourself. The only situation you should consider rolling your own is if you can articulate a very specific, mission-critical need that the STL algorithms don't satisfy.

Edited to add: (Okay, so not really really always, but if you have to ask whether you should use STL, the answer is "yes".)

like image 95
David Avatar answered Oct 02 '22 12:10

David