Wednesday, 24 July 2013

Useful C++ helper functions

My brain sucks. It can remember the lyrics to songs or the power draw of a electronic component, but I keep forgetting those useful helper function you sometimes need. This sends me off Google again, searching through excellent sites like StackOverflow etc. Time to make a list...

  • Remove characters from a string:
#include <algorithm>
#include <iterator>
std::string result;
std::remove_copy(input.begin(), input.end(), std::back_inserter(result), 'a');
  • Replace characters in a string:
std::replace(input.begin(), input.end(), 'a', 'b');
  • Convert integer to std::string without the << operator:
std::to_string((long long)number);
  • Create a shared_ptr managing an array:
std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>(new unsigned char[size], [](unsigned char *p) { delete[] p; });

(You must use a custom deleter, because by default delete is called, not delete[]. Here a lambda function is passed to the shared_ptr constructor)
  • Advance an iterator by a number:
std::vector<int> list;
std::vector<int>::const_iterator iter = list.cbegin();
advance(iter, 5);
  • Append std::vector elements from one vector to another:
std::vector<int> destination;
std::vector<int> source;
destination.insert(destination.end(), source.cbegin(), source.cend());

(Why there is no push_back() overload for this is beyond me...)
  • For loops and auto
std::vector<int> foo;
for (auto fooIt = foo.cbegin(); fooIt != foo.cend(); ++fooIt) {
... }

Needs only one line and will still work when you change the type of foo...
  • Output all content of a std::vector to a stream
std::vector<std::string> words; //contains some strings
std::stringstream ss;
std::copy(words.begin(), words.end(), std::ostream_iterator(ss));

No comments:

Post a Comment