C++ Standard library

Conversions and String manipulation

int to std::string

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

Length and first N chars of UTF-8 strings

unsigned int strlenUtf8(std::string str) {
	const char* s = str.c_str();
	unsigned int len = 0;
	while (*s) len += (*s++ & 0xc0) != 0x80;
	return len;
}
 
std::string firstChars(std::string str, unsigned int maxLen) {
	const char* s = str.c_str();
	stringstream ss;
	unsigned int len = 0;
	while (*s) {
		len += (*s & 0xc0) != 0x80;
		if (len > maxLen) {
			return ss.str();
		}
		ss << *s++;
	}
	return ss.str();
}

Example :

std::string s("bébé");
cout << "s.length()=" << s.length() << endl;
cout << "strlenUtf8(s)=" << strlenUtf8(s) << endl;
cout << "s.substr(0, 2)=" << s.substr(0, 2) << endl;
cout << "firstChars(s,2)=" << firstChars(s,2) << endl;

returns :

s.length()=6
s.substr(0, 2)=b
strlenUtf8(s)=4
firstChars(s,2)=bé

Find the type of an object

std::string type(typeid(object).name());
cout << "object is of type " << type;

(Note : See Boost section to obtain the demangled version)

Data structures

Check if vector contains value

#include <algorithm>
 
if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Insert value in map

std::map<char,int> mymap;
mymap.insert(std::make_pair('a', 100));

Check if map contains key (and get the corresponding value)

#include <string>
 
map<int,std::string>::iterator it = m.find("super");
if(it != m.end())
{
   return it->second;
}
if (m.count("super") == 1) {
   return m.at("super");
}

OOP

static constants

file.cpp
const string HafasFileFormat::Exporter_::DIDOK_DATA_SOURCE_NAME = "DIDOK";
file.hpp
class HafasFileFormat {
   class Exporter_ {
      private:
         static const std::string DIDOK_DATA_SOURCE_NAME;
   }
}

Other

Random boolean

srand(time(0)); // Only run this once at the beginning !
bool yay = rand() % 2;
Print/export