The C++ Standard Library

Nicolai M. Josuttis

Mentioned 9

A proven best-seller, updated for the new standard: still the most practical C++ Standard Library tutorial and most complete reference * *Thoroughly documents each library component incorporated in the brand-new C++ standard. *Clearly explains complex concepts, and presents the practical detail programmers need to use the Standard Library effectively. *Contains many examples of working code, all available for download at an accompanying website. The C++ Standard Library, 2/e, doesn't just provide comprehensive documentation of every library component associated with the newest C++ standard: it also offers clearly-written explanations of complex concepts, reviews practical programming details needed for effective use, and presents many useful examples of working code - all of them available for download. Fully updated to reflect the newest elements of the C++ Standard Library incorporated into the full ANSI/ISO C++ language standard, this book examines containers, iterators, function objects, STL algorithms, special containers, strings, numerical classes, internationalization, the IOStream library, and much more. Every component is presented in depth: Josuttis explains its purpose and design, presents crystal-clear examples, identifies traps and pitfalls, and offers exact signatures and definitions of its classes and functions. Comprehensive, detailed, readable, and practical, Josuttis' The C++ Standard Library has established itself as the definitive book on the topic: working developers will find this new edition even more useful.

More on Amazon.com

Mentioned in questions and answers.

This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year.

Unlike many other programming languages, which are often picked up on the go from tutorials found on the Internet, few are able to quickly pick up C++ without studying a well-written C++ book. It is way too big and complex for doing this. In fact, it is so big and complex, that there are very many very bad C++ books out there. And we are not talking about bad style, but things like sporting glaringly obvious factual errors and promoting abysmally bad programming styles.

Please edit the accepted answer to provide quality books and an approximate skill level — preferably after discussing your addition in the C++ chat room. (The regulars might mercilessly undo your work if they disagree with a recommendation.) Add a short blurb/description about each book that you have personally read/benefited from. Feel free to debate quality, headings, etc. Books that meet the criteria will be added to the list. Books that have reviews by the Association of C and C++ Users (ACCU) have links to the review.

Note: FAQs and other resources can be found in the C++ tag info and under . There is also a similar post for C: The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

  • A Tour of C++ (Bjarne Stroustrup) (EBOOK) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction into the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach at teaching the language.) [Review]

  • Thinking in C++ (Bruce Eckel) Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they’re marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at (http://www.computersciencelab.com/Eckel.htm), but it’s apparently not maintained.

* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

Best practices

  • Effective C++ (Scott Meyers) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]

Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using nonmember functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition is scheduled for 2017. [Review]


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multimethods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications.

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by typetraits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much alike it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review]

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14 References:

  • The C++ Standard (INCITS/ISO/IEC 14882-2011) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. As usual, the first release was quite expensive ($300+ US), but it has now been released in electronic form for $60US.

  • The C++14 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++17.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++1y/C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly a good read, if it only was up to date. It was written long before C++98, and misses on many features (e.g. namespaces) important for large scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is expected in 2015.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however this is book goes through the entire C++ standard of the time explaining the rationale, the possible implementations and features of the language. This is not a book not learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

For a platform-independent model layer, I have hierarchical data (strings, actually) that look like this:

  • Item A
    • SubItem A
    • SubItem B
    • SubItem C
      • SubSubItem A
      • SubSubItem B
    • SubItem D
  • Item B
  • Item C

Now, within each "level" (Item, SubItem, SubSubItem, etc.) the items need to be sorted alphabetically.

Seems a simple solution would be to create a simple class with a sorted std::Vector or std::MultiMap to track its Children, and a pointer to its Parent. (and one root item). I would need to generally iterate through each item's children in a forward direction.

After construction/sorting, I do not need to add or delete items. Generally small numbers of items (hundreds).

This is for model organization of the backing data of an outline-style control.

Rolling a simple class would be easy, but this is such a common pattern — isn't there already a ready-made STL container with this behavior?

No. Don't mean to be curt, but that is the answer; see e.g. Josuttis, or the standard. You'll have to create a class which parent/child pointers along the lines you suggested and use a vector or other standard container of those.

By accident I found out that I can use read and write on socket descriptors. Can I somehow (ab)use the fstream mechanism to output data into the socket descriptor?

The standard file stream doesn't support use of a file descriptor. However, the I/O stream classes make it reasonably easy to create your own abstraction which allows creating your own sources of or destination for characters. The magic class is std::streambuf whose responsibility is to buffer characters and read or write characters at appropriate times. Nicolai Josuttis's "The C++ Standard Library" has a detailed description of how to do so (the basis of which I contributed to Nico many years ago). A simple implementation of a stream buffer using a socket for reading and writing would look something like this:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <streambuf>
#include <cstddef>
#include <unistd.h>

class fdbuf
    : public std::streambuf
{
private:
    enum { bufsize = 1024 };
    char outbuf_[bufsize];
    char inbuf_[bufsize + 16 - sizeof(int)];
    int  fd_;
public:
    typedef std::streambuf::traits_type traits_type;

    fdbuf(int fd);
    ~fdbuf();
    void open(int fd);
    void close();

protected:
    int overflow(int c);
    int underflow();
    int sync();
};

fdbuf::fdbuf(int fd)
  : fd_(-1) {
    this->open(fd);
}

fdbuf::~fdbuf() {
    this->close();
}

void fdbuf::open(int fd) {
    this->close();
    this->fd_ = fd;
    this->setg(this->inbuf_, this->inbuf_, this->inbuf_);
    this->setp(this->outbuf_, this->outbuf_ + bufsize - 1);
}

void fdbuf::close() {
    if (!(this->fd_ < 0)) {
        this->sync();
        ::close(this->fd_);
    }
}

int fdbuf::overflow(int c) {
    if (!traits_type::eq_int_type(c, traits_type::eof())) {
        *this->pptr() = traits_type::to_char_type(c);
        this->pbump(1);
    }
    return this->sync() == -1
        ? traits_type::eof()
        : traits_type::not_eof(c);
}

int fdbuf::sync() {
    if (this->pbase() != this->pptr()) {
        std::streamsize size(this->pptr() - this->pbase());
        std::streamsize done(::write(this->fd_, this->outbuf_, size));
        // The code below assumes that it is success if the stream made
        // some progress. Depending on the needs it may be more
        // reasonable to consider it a success only if it managed to
        // write the entire buffer and, e.g., loop a couple of times
        // to try achieving this success.
        if (0 < done) {
            std::copy(this->pbase() + done, this->pptr(), this->pbase());
            this->setp(this->pbase(), this->epptr());
            this->pbump(size - done);
        }
    }
    return this->pptr() != this->epptr()? 0: -1;
}

int fdbuf::underflow()
{
    if (this->gptr() == this->egptr()) {
        std::streamsize pback(std::min(this->gptr() - this->eback(),
                                       std::ptrdiff_t(16 - sizeof(int))));
        std::copy(this->egptr() - pback, this->egptr(), this->eback());
        int done(::read(this->fd_, this->eback() + pback, bufsize));
        this->setg(this->eback(),
                   this->eback() + pback,
                   this->eback() + pback + std::max(0, done));
    }
    return this->gptr() == this->egptr()
        ? traits_type::eof()
        : traits_type::to_int_type(*this->gptr());
}

int main()
{
    fdbuf        inbuf(0);
    std::istream in(&inbuf);
    fdbuf        outbuf(1);
    std::ostream out(&outbuf);

    std::copy(std::istreambuf_iterator<char>(in),
              std::istreambuf_iterator<char>(),
              std::ostreambuf_iterator<char>(out));
}

I have an abstract class in my project, its derivatives is used for input/output to different locations. It has virtual methods read and write.

virtual unsigned read(void *buf, unsigned len) = 0;
virtual void write(const void *buf, unsigned len) = 0;

I need a kind of an adapter between std streams (std::istream and std::ostream) and this class to redirect input/output to these methods.

So, for example, if

mystream << "some output";

is called, it will call the write method.

I guess i should overload std::istream and std::ostream or std::streambuf, but not sure which methods.

What is the better way to implement this?

There are lots of simple but not flexible ways of doing it. Most of these solution will not leverage istream or ostream. For instance, overloading the << operator is one way. The drawback is that you will have to implement this operator for all the usual types, and for all the standard manipulators, and so on. It may become a great burden.

This is sad because the whole thing about istream and ostream is only to parse and format not to do input or output. The I/O responsibility is given to the streambuf. And your task calls for a custom implementation of streambuf which uses your read and write methods.

The discussion is too long for such a small format as a stackoverflow answer but you can find good pointers in the following references.

References

Note

As advised, using boost.iostreams maybe a good fit, but I don't know it enough.

In the book at page 91 in chapter i have read this phrase about shared_from_this():

The problem is that shared_ptr stores itself in a private member of Person’s base class, enable_shared_from_this<>, at the end of the construction of the Person.

I don't understand two things here:

  1. who is this shared_ptr which stores itself?
  2. how he can store itself anywhere at the end of the construction of the Person? I think construction of the Person ends up with the last statement of its constructor which written by me.

I understand that there is weak_ptr which hasn't been initialized yet.

EDIT: Thanks to Angew! shared_from_this will work only after first shared_ptr to Person was created. This shared_ptr will check if Person class inhereted from enable_shared_from_this, and if yes then initialize its internal weak_ptr.

The reason is simple: in object X, enable_shared_from_this works by initialising a hidden weak_ptr with a copy of the first shared_ptr which points to object X. However, for a shared_ptr to be able to point to X, X must already exist (it must be already constructed). Therefore, while the constructor of X is running, there is yet no shared_ptr which enable_shared_from_this could use.

Take this piece of code:

std::shared_ptr<Person> p(new Person());

Before the constructor of p (of the shared_ptr) is even called, its argument must be evaluated. That argument is the expression new Person(). Therefore, the constructor of Person runs before the constructor of p has even begun—before there is any shared_ptr object to which enable_shared_from_this could bind.

I would like to know if the attached code correctly implements a custom C++ input iterator.

While I am able to compile it successfully and obtain the expected results, I am doubtful that I have fully covered all the input iterator concept requirements.

My concrete question: is this how you implement a custom C++ input iterator?

I have studied other answers to similar questions, and have read the relevant section in Josuttis book. Unfortunately those resources do not offer more extensive information, and even though I am able to code something that "seems to work", I do not trust my own code.

The example implements an input iterator which yields n values in [initial, final]; the iterator is named after the well-known Matlab function offering the same functionality:

#include <cstddef>   // for std::size_t
#include <iterator>  // for std::iterator
#include <iostream>  // for std::cout
#include <algorithm> // for std::copy
#include <vector>    // for std::vector


template<typename T = double>
class linspace_iterator
    : public std::iterator<std::input_iterator_tag,T> {
 public:

  /// @brief Constructs the end-of-linspace iterator.
  explicit linspace_iterator()
      : m_initial(0),
        m_final(0),
        m_step(0),
        m_N(0),
        m_k(0) { }

  /// @brief Constructs an iterator yielding N equally-spaced values
  /// in @p [initial, final].
  explicit linspace_iterator(T initial, T final, std::size_t N = 100)
      : m_initial(std::move(initial)),
        m_final(std::move(final)),
        m_step((final - initial) / (N - 1)),
        m_N(std::move(N)),
        m_k(0) { }

  T operator*() const {
    return m_initial + m_k * m_step;
  }

  linspace_iterator<T>& operator++() {
    m_k++;
    return *this;
  }

  linspace_iterator<T>& operator++(int n) {
    m_k += n;    
    return *this;
  }

  bool operator !=(linspace_iterator<T>&) const { return m_k != m_N; }
  bool operator ==(linspace_iterator<T>&) const { return m_k == m_N; }

 private:
  const T           m_initial;
  const T           m_final;
  const T           m_step;
  const std::size_t m_N;
  std::size_t       m_k;
};

template<typename Container>
Container linspace(typename Container::value_type initial,
                   typename Container::value_type final,
                   std::size_t N = 100) {
  return Container(linspace_iterator<typename Container::value_type>(initial, final, N),
                   linspace_iterator<typename Container::value_type>());
}

template<typename Container>
inline void show(const Container& c) {
  for(const auto & item : c) {
    std::cout << item << " ";
  }
  std::cout << std::endl;
}

int main() {
  std::cout << "Copy linspace to std::cout (5 values in [0, 7])" << std::endl;
  std::copy(linspace_iterator<>(0, 7, 5),
            linspace_iterator<>(),
            std::ostream_iterator<double>(std::cout, ", "));


  std::cout << "A vector with 100 values in [-1, 1]" << std::endl;
  std::vector<double> data(linspace_iterator<>(-1, 1),
                           linspace_iterator<>());
  show(data);

  std::cout << "A vector with 100 values in [-5.0f, 2.0f]" << std::endl;
  auto myvec = linspace<std::vector<float>>(-5.0f, 2.0f);

  show(myvec);

  std::cout << "Addressing @mythagel's comment" << std::endl;
  for(auto it = linspace_iterator<>(0, 7, 5), end = linspace_iterator<>(); it != end; ++it) {
    std::cout << *it << ' ' << *it << '\n';
  }
  return 0;
}

Using the following command:

{cxx} linspace-itertor.cpp -std=c++11 -Wall -Wextra -Werror -pedantic

(where {cxx} = g++ 4.8.2, icpc 14.0.2, and clang++ 3.6.0) the code compiles successfully (no warnings, no errors).

Output:

Copy linspace to std::cout (5 values in [0, 7])
0, 1.75, 3.5, 5.25, 7, A vector with 100 values in [-1, 1]
-1 -0.979798 -0.959596 -0.939394 -0.919192 -0.89899 -0.878788 -0.858586 -0.838384 -0.818182 -0.79798 -0.777778 -0.757576 -0.737374 -0.717172 -0.69697 -0.676768 -0.656566 -0.636364 -0.616162 -0.59596 -0.575758 -0.555556 -0.535354 -0.515152 -0.494949 -0.474747 -0.454545 -0.434343 -0.414141 -0.393939 -0.373737 -0.353535 -0.333333 -0.313131 -0.292929 -0.272727 -0.252525 -0.232323 -0.212121 -0.191919 -0.171717 -0.151515 -0.131313 -0.111111 -0.0909091 -0.0707071 -0.0505051 -0.030303 -0.010101 0.010101 0.030303 0.0505051 0.0707071 0.0909091 0.111111 0.131313 0.151515 0.171717 0.191919 0.212121 0.232323 0.252525 0.272727 0.292929 0.313131 0.333333 0.353535 0.373737 0.393939 0.414141 0.434343 0.454545 0.474747 0.494949 0.515152 0.535354 0.555556 0.575758 0.59596 0.616162 0.636364 0.656566 0.676768 0.69697 0.717172 0.737374 0.757576 0.777778 0.79798 0.818182 0.838384 0.858586 0.878788 0.89899 0.919192 0.939394 0.959596 0.979798 1
A vector with 100 values in [-5.0f, 2.0f]
-5 -4.92929 -4.85859 -4.78788 -4.71717 -4.64646 -4.57576 -4.50505 -4.43434 -4.36364 -4.29293 -4.22222 -4.15152 -4.08081 -4.0101 -3.93939 -3.86869 -3.79798 -3.72727 -3.65657 -3.58586 -3.51515 -3.44444 -3.37374 -3.30303 -3.23232 -3.16162 -3.09091 -3.0202 -2.9495 -2.87879 -2.80808 -2.73737 -2.66667 -2.59596 -2.52525 -2.45455 -2.38384 -2.31313 -2.24242 -2.17172 -2.10101 -2.0303 -1.9596 -1.88889 -1.81818 -1.74747 -1.67677 -1.60606 -1.53535 -1.46465 -1.39394 -1.32323 -1.25253 -1.18182 -1.11111 -1.0404 -0.969697 -0.89899 -0.828283 -0.757576 -0.686869 -0.616162 -0.545455 -0.474748 -0.404041 -0.333333 -0.262627 -0.191919 -0.121212 -0.0505052 0.0202017 0.090909 0.161616 0.232323 0.30303 0.373737 0.444444 0.515152 0.585858 0.656566 0.727273 0.797979 0.868687 0.939394 1.0101 1.08081 1.15152 1.22222 1.29293 1.36364 1.43434 1.50505 1.57576 1.64646 1.71717 1.78788 1.85859 1.92929 2
Addressing @mythagel's comment
0 0
1.75 1.75
3.5 3.5
5.25 5.25
7 7

The C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++.

The C++ Standard library should not be confused with C++ standard template library. is a subset of C++ Standard Library.

Books

The Standard Template Library, or STL, is a C++ library of generic containers, iterators, algorithms, and function objects. Originally designed by Alexander Stepanov and Meng Lee and published by HP in 1995. Large parts of the STL were adopted with modifications into the ISO C++ Standard Library.

Note that the name STL is ambiguous, as it may refer to different things. The following are the typical intended meanings (suggested tagging in brackets):

The last two definitions are, strictly speaking, incorrect; the C++ standard never mentions either "STL" or "Standard Template Library". In practice, however, people rarely need to refer to the HP library, and so "STL" is nearly always used to describe the STL-derived parts of the standard library instead (the algorithms, iterators and containers), or the template portions.

Programming Elements

Most of the STL's programming elements are in std namespace. Containers, algorithms, iterators and other helping constructs exist in various headers, but they all are inside std namespace. The basic and most common used container, vector can be used by:

  • Including the header <vector>
  • Declaring the variable by full scoped name:

    std::vector<int> IntV;

    or by including whole of std:

    using namespace std;
    vector<int> IntV;

    or pulling specific symbol:

    using std::vector;
    vector<int> IntV;

All other programming elements can be used by similar pattern.

Beauty of STL is that Containers (list, unordered_map etc.), Algorithms (sort, count_if), Iterators (reverse iterator, const iterator etc.) are not dependent on each other but can be used together without knowing internals of other element. Containers and Algorithms are connected by iterators.

Resources

*This reference is non-normative.

Books

I recently rented a book from my local library for c++, the books title is: "Data Structure Programming with the standard template library in c++" by Joseph Bergin. The problem is when i checked the publication date it read 1998, which is a pretty huge time frame given the speed of computer advances today. Will this book hurt me or help me? Here is an excerpt from an algorithm in my book:

//  THIS IS AN ALGORITHM EXPLAINED AS SELECTION SORT
template <class T>
void selectionSort(T* start, T* end)                //first off, i notice an excessive use of pointers, when usually 
{   for(T* where = start ; where < end ; where++)   // im told to work around pointers if i dont need to use them
    {   T* loc = where;                             //weird bracket formatting(old practice i would guess?)
        T small = *loc;
        for                                         //very strange method of organizing for loops used in the book
        (   T* inner = where + 1;
            inner < end;
            inner++;
        )
            if(*inner < *loc)
            {   loc = inner;
                small = *loc;
            }
        *loc = *where;
        *where = small;
    }
}

this code uses strange methods in order to make a selection sort. Pointers could easily be replaced with normal values, yet the book loves the use of pointers and odly formatted for loops. How far off is this code from a modern C++11 approach to a selection sort with arrays?

*They also declare all of their variables with a _ prefix, does this do anything special to variables? examples of declared vars:

int _Num1;
float _Select;

You should get a new book, but that doesn't mean your current book is necessarily harmful.

The C++ language is defined by a Standard, which is written by an international committee. Compilers implement this Standard to varying degrees, but they all follow the C++ Standard more or less.

Since 1998, there have been not one but two new Standards produced -- one in 2003 (often called C++03), and one just recently in 2011 (C++11). The fundamental idioms that existed in 1998 are still relevant today, so learning those is still important. But there have been substantial changes to the Standard Library, including the parts of the Standard Library that many people (mistakenly) refer to as the "STL". There has been refinement to many of the idioms known in 1998 as our experience with the language grows, and there are new idioms possible in C++11 that weren't possible in 1998.

There is an excellent Wikipedia article that enumerates many of the differences between C++11 and C++03, and there are even more differences in C++ from 1998.

Here is one new book that I have been reading. The C++ Standard Library: A Tutorial and Reference (2nd Edition)