# C9 Lectures: Stephan T. Lavavej - Standard Template Library (STL), 7 of n

- Posted: Oct 22, 2010 at 10:27 AM
- 80,858 Views
- 37 Comments

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

- Posted: Oct 22, 2010 at 10:27 AM
- 80,858 Views
- 37 Comments

- To download, right click the file type you would like and pick “Save target as…” or “Save link as…”

- It's an easy way to save the videos you like locally.
- You can save the videos in order to watch them offline.
- If all you want is to hear the audio, you can download the MP3!

- If you want to view the video on your PC, Xbox or Media Center, download the High Quality MP4 file (this is the highest quality version we have available).
- If you'd like a lower bitrate version, to reduce the download time or cost, then choose the Medium Quality MP4 file.
- If you have a Windows Phone, iPhone, iPad, or Android device, choose the low or medium MP4 file.
- If you just want to hear the audio of the video, choose the MP3 file.

Right click “Save as…”

Welcome to another installment of C9 Lectures covering the powerful general C++ library, STL. Joining us once again is the great Stephan T. Lavavej, Microsoft's keeper of the STL cloth (this means he manages the partnership between the owners of STL (dinkumware) and Microsoft, including, of course, bug fixes and enhancements to the STL that ships as part of Visual C++). Simply, Stephan is a C++ library developer.

As is Stephan's nature, he elaborates on technical details in very substantive way. The Standard Template Library, or*STL*, is a C++ library of container classes, algorithms, and iterators. STL provides many fundamental algorithms and data structures. Furthermore, the STL is a general-purpose library: its components are heavily parameterized, such that almost every component in the STL is a *template*.

In **part 7**, Stephan continues to dig into STL algorithms, specifically insert iterators, sorting and related functions.

Enjoy! Learn!

Books mentioned by Stephen:

The C++ Standard Library: A Tutorial And Reference by Nicolai M. Josuttis

Effective STL by Scott Meyers

**[STL Introduction lecture links]**

Part 1 (sequence containers)

Part 2 (associative containers)

Part 3 (smart pointers)

Part 4 (Nurikabe solver) - see Wikipedia's article and Stephan's updated source code

Part 5 (Nurikabe solver, continued)

Part 6 (algorithms and functors)

Part 7 (algorithms and functors, continued)

Part 8 (regular expressions)

Part 9 (rvalue references)

Part 10 (type traits)

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation,
please create a new thread in our Forums,

or
Contact Us and let us know.

## Follow the Discussion

Oops, something didn't work.

## What does this mean?

Following an item on Channel 9 allows you to watch for new content and comments that you are interested in. You need to be signed in to Channel 9 to use this feature.## What does this mean?

Following an item on Channel 9 allows you to watch for new content and comments that you are interested in and view them all on your notifications page.sign up for email notifications?

Why does the MinMax function have that complexity?

O(n)

or if the STL would let you do

Best Case: O(log n) ' both are the last element.

Worst Case: O(2 log n) ' first and last elements.

Average Case: 0( (2 log n) / 3)

If I've missed something in the algorithms implementation, could you point be to a source (as I would be interesting in look at it.)

Because binary search only works on sorted ranges?

minmax_element() has O(N) asymptotic complexity, but it provides an exact complexity guarantee that's even better. Your first implementation performs 2N comparisons. The STL performs at most 1.5N comparisons. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3126.pdf 25.4.7 [alg.min.max]/36.

As for your second implementation, lower_bound() and upper_bound() require sorted sequences, while minmax_element() accepts arbitrary sequences. Finding the minimum and maximum of a sorted sequence can be done in O(1) time. :->

Stephan, at 6:39 you write *it++ = elem. I wonder if this code is indeed well-defined for output iterators and opened a question on stack overflow. Could you comment on this issue? Thanks!

I made slight booboo in the algorithm I forgot to add the element you are looking for.

Can't get link to work, Timestamp 33m00

The section where you are on about the lower and upper bounds of a group of elements (equal to the value you're looking for) in a sorted sequence y.

Not the lowest and highest values.

That's straight out of the Output Iterator requirements. N3126 24.2.4 [output.iterators] Table 105 "Output iterator requirements (in addition to Iterator)" contains "*r++ = o".

AdamSpeight2008: You're thinking of equal_range(), which is required to behave as if it returns make_pair(lower_bound(first, last, value), upper_bound(first, last, value)), and is required to perform at most 2 * log2(last - first) + O(1) comparisons (N3126 25.4.3.3 [equal.range]/2-3).

STL implementations are permitted to perform fewer comparisons, and ours does.

Ah! I see where the _min iterator would be affected, so let's say a copy is passed to UB.

Let see if I've got this right minmax_element returns the smallest and largest element from an underordered sequece?

I found out hows it is implemented,

Here's an example:

Just thank you, STL

Same here :)

Stephan, are you going to tell us everything about functors in a next episode?

There's always more to tell. I'm getting close to exhausting the simple topics, so it's probably time to begin introducing C++0x features. Lambdas (which I've shown a little), perfect forwarding, and perfect returning are all relevant to functors.

Is there anything else that people want to see?

@STL:

Good interesting stuff as always

> Is there anything else that people want to see?

1. perhaps a how to and how not to write ex a base64 encoder/decoder that interacts with the stl streams

2. (perhaps this is more of a question) when to use lambdas and when to use bind, bind2nd, mem_fn.

i've read that lambdas can replace these functions but when should you use functions like bind, bind2nd,mem_fn. instead of lambdas ?

3. Talk more about common mistakes / gotchas

4. How to optimize the usage of STL, ex making sure you use the right container/algorithm for the right job, etc..

5. How not to use the STL, guess this is the same as 3.

6. How to add new features / functionality to complement the STL.. ( connected with 1. )

How about that ?

At least the need for manual loops has almost been completely eliminated .

I've been spraining my brain recently with how to implement Shear-sort, its absolutely cool,entertaining and fast. Shell & Radix soort used to be my favs, but now its shearsort. Have a look at it, you also may find it fairly entertaining.

@STL: I/O handle, Socket, file Processing in the STL(Standard Template Library)..

But I'd like to close and learn to the "vector, string" and Lambda expression for char* processing.

As well, furthermore , Stephan tries to emphasize that "C++(STL) is more effective and efficient than other languages." just my hope or wish..

Thank you for your lectures.

@STL: Template metaprogramming, as mentioned in the previous Video comments (you answered that it might be in part 8 )

@STL: Thanks for another great lecture.

> Is there anything else that people want to see?

Aside from what you've just mentioned, I'd like clarification on using r-value reference. MSDN help doesn't really show how to use it effectively, just syntactically.

Thanks for the suggestions!

[Mr Crash]

> when to use lambdas and when to use bind, bind2nd, mem_fn.

> i've read that lambdas can replace these functions but when should you use functions like bind, bind2nd,mem_fn. instead of lambdas ?

bind() supersedes bind1st() and bind2nd().

mem_fn() supersedes mem_fun() and mem_fun_ref().

But lambdas supersede all of them. Lambdas are easier to read, easier to write, and more efficient. In the few cases where lambdas aren't sufficient, you should use handwritten functors. (One case is a map's comparator, where you want an easily named and default-constructible type. Other cases include templated or recursive functors.)

[HeavensRevenge]

> Shell & Radix soort used to be my favs, but now its shearsort.

My favorite special-purpose sort uses a suffix tree to sort the suffixes of a string. A string of length N has N suffixes ("meow" has the suffixes "meow", "eow", "ow", and "w"; one convention is to count the whole string, but not the empty string, as a suffix). Using a general-purpose sort takes O(N^2 log(N^2)) = O(2 * N^2 log(N)) = O(N^2 log(N)), which is slower than quadratic. (It would perform N log N comparisons, but each comparison takes O(N) time in the worst case; consider the string "aaaaaaaab".) Suffix trees take O(N) time. That's not a typo, it really is linear time.

@STL:

"Is there anything else that people want to see?"

Wide character support, e.g. wstring, wofstream etc.

Locales

For general purpose, I believe the complexity of shearsort is something like O(n

^{^1/2 (}log n)) or equivalent to: Im glad my tablet functionality comes in handy every once in a whileBut I AM quite pleased to have heard you mention that your STL implements an IntroSort its pretty awesome since SGI's STL implementation has IntroSort as the default too.

This URL is awesome since you can customize, this is how I compare sorts haha, when their bad implementation doesn't bug out of course

http://home.westman.wave.ca/~rhenry/sort/duel.php?width=600&height=1000&alg1=ShearSort&alg2=IntroSort

I made it be around screen width(each 600 wide), both sorts using 1000 entries to sort, Comparing side-by-side my new fav Shearsort with the also impressive IntroSort. The bigger N, the better Shearsort can do, since its complexity stays way down, and is excellently-parallel n-way per "shear".

[WalderFrey]

> Wide character support, e.g. wstring, wofstream etc. Locales

Unfortunately, that's a complicated topic, I'm not an expert there (I know stuff, but I like to teach things only when I'm an expert), and iostreams/locales aren't part of the STL proper (string is a borderline case). So I don't think I'll be covering Unicode in this series.

[HeavensRevenge]

> For general purpose, I believe the complexity of shearsort is something like O(n^1/2 (log n))

The best that a serial general-purpose sort can do is O(N log N). That's a theorem that CS students prove in Algorithms 101. std::sort() is now required by C++0x to be worst-case O(N log N). In C++98/03, it was permitted to be average O(N log N), worst-case O(N^2), i.e. the behavior of a plain quicksort.

The STL currently doesn't contain parallel algorithms. I've asked for parallel_sort() from the Concurrency Runtime team, but haven't gotten it yet. :->

Recursive lambdas don't actually look so bad:

std::function<int(int)> factorial = [&factorial](int n) -> int { return n <= 1 ? 1 : n * factorial(n-1);};

std::cout << factorial(4);

They do not work with "auto" however... And you couldn't just slap this inside an algorithm as you need to define a variable, and if you're doing that anyway you may as well just be making a named functor for it.

Source: http://cottonvibes.blogspot.com/2010/07/c0x-autos-lambdas-and-lambda-recursion.html

I would've much rather seen the standard library draft text on the monitor rather than your wm7 advertisement.

If you watch carefully, near the end of the video, I accidentally brushed the TV's capacitive buttons with my arm, switching its input from my laptop (which has a background of the Carina Nebula) to one of the studio's computers (which has the background that you saw). I didn't even notice that this had happened until after I had finished recording the video, as my right eye is blind.

Didn't even realize that it was a mistake nor did I realize that your right eye is blind.

...impatiently waiting for your next video! Keep up these awesome videos!

Seconded!

On Friday (Nov 5), I filmed Part 8 (regex) and Part 9 (rvalue references). They'll be coming your way soon!

@STL: Cool, that's great!

@STL: > Is there anything else that people want to see?How about making a simple yet extensible calculator using STLi think a lot the STL will come in handy.

What do you think about that suggestion ?

Keep the videos coming, please :)

Starting to feel the effects of withdrawal and it ain't pretty!

Agreed, I need my STL fix

now!10 days later, still no video

Oh well, the joy of anticipation...

Yes, except that the joy could be in anticipation for the 9th Video, after having watched the 8th video

Oh Stephan, where art thou?

I'm in Part 8, talking about regex: http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-8-of-n

## Remove this comment

## Remove this thread

close