Pete Ware

Tech, NYC & Politics

Tag: stl

Passing extra arguments to output operator

I usually implement the output operator for a class, operator<<().
I find it useful for debugging and regression testing purposes.
Occasionally when defining a class hierarchy with polymorphism in mind
I’ll instead define a virtual print() method.

Here’s the typical implementation:
Continue reading

C++ test for within

I found myself having to write a bunch of range checking code like this:

so I wrote this simple function.
Continue reading

Switching keys in values in a map

A functor that reverses a pair: first becomes second,
second becomes first. Useful for switching
from a map to another map (or multimap in this example) where
the value becomes the key and the key the value.

And the actual code:

Getting the keys from a std::map

So last week I wrote about initializing a std::map from two std::vectors. How about doing the reverse? How do I get a list of the keys or a list of the values into a vector?

So I wrote a functor, based on std::unary_function, that returns the pair.first and another that returns the pair.second:
Continue reading

Functor for deleting objects

In a destructor for a class, I had a std::vector of pointers that I wanted to delete. I started to write the usual for(;;) loop and realized I do this often enough I should make it easy to use std::for_each().

Here’s the functor (based on std::unary_function):

And here’s some sample code using it:

I added a return of true because some other template code wasn’t happy about “return void” — supposedly something fixed in recent compilers.

A better output_iterator

I was using the std::stream_iterator, for example:

It has the “,” after the last item.

So here’s an implementation that doesn’t append the seperator after the last one:

And here’s the corresponding code to use it:

Copying a std::vector into a std::map

I had two vector’s with the first being the keys and the second being the values. It took a couple tries before I got the STL working for me!

The first thing was to check if the std::map constructors had something useful. It certainly seems like taking two sets of iterators would be a great way to initialize a map. No such luck.

So how about one of the std algorithms to copy the keys and values into the map? std::copy seemed likely but it only takes a single sequence. A little more digging and std::transform. The second version of std::transform takes two sequences, an output iterator, and a binary function to convert the two values from the two sequences into something that can be inserted into the output iterator. Perfect.

So how to turn the two values into a pair suitable for std::map? The std::make_pair
is exactly what is needed. The hard part is getting the syntax so you can pass it as a function: make_pair in this example.

So the code finally looks like:

© 2017 Pete Ware

Theme by Anders NorenUp ↑