Monday, April 10, 2006

STL short / one liners

A very nice collection of wrappers is available on Stackoverflow.

1. Copy everything in the a container to std::cout (e.g. std::set<std::string> c; )
std::copy (c.begin(), c.end(), std::ostream_iterator <std::string> (std::cout, "\n"));

2. Clear vector v and minimize its capacity (potential number of elements it can hold without resizing).
vector <std::string>().swap (v); Yes! It is a swap with an empty temporary!!

3. Remove all integers of value = 0xDeadBeef;
std::erase (std::remove (c.begin(), c.end(), value), c.end());
This is known as erase-remove idiom.

4. Invoke a member function on all the elements of the container.
std::for_each (c.begin(), c.end(), std::mem_fun (&Class::function));

5. Copy one container to other
std::copy(V.begin(), V.end(), L.begin());

6. Fill an array with random numbers
std::generate(V.begin(), V.end(), rand);

7. Read a file of integers in a set
std::istream_iterator <int> data_begin (std::cin), data_end;
std::set <int> S (data_begin, data_end);

OR
std::set <int> data ((istream_iterator <int> (datafile)),istream_iterator <int> ());

OR
istream_iterator <int> start (cin), end;
copy (start, end, std::back_inserter (v));

8. Reading entire file in one go.

Solution 1:
std::istreambuf_iterator < char > begin(std::cin), end;
std::string str(begin, end);

Solution 2:
std::ostringstream temp;
std::ifstream infile ("file.txt");
temp << infile.rdbuf();
std::string str = temp.str();

1 comment: