User Tools

Site Tools



Loop over a Sequence

#include <boost/foreach.hpp> vector<string> ids; 
BOOST_FOREACH(string id, ids) {
// do something with id

Loop over a Mapping

#include <boost/foreach.hpp> 
#include <boost/tuple/tuple.hpp> 
std::map<int, std::string> theMap;  
int key;  
std::string value;  
BOOST_FOREACH(boost::tuples::tie(key, value), theMap) {
std::cout << key << " => " << value << "\n";


Split a string

#include <boost/algorithm/string.hpp>
vector<string> splitResult;
boost::split(splitResult,"wir;funktionieren;automatik;;",boost::is_any_of(";,.")); // results in |wir|funktionieren|automatik|

Note Boost's split behaviour where two separators meet in a string: split creates an empty element to signal there's no data between those two separators. Thus it's possible to reconstruct the original string.

Join a vector of strings

#include <boost/algorithm/string.hpp> 
vector<string> data_bits; 
string data_copy = boost::join(data_bits,",");

Lexical cast

#include <boost/lexical_cast.hpp> int i = boost::lexical_cast<int>("2");


Finding a file



Append vector to other vector

vector<int> a,b;

BOOST-List/map hybrid

Sometimes a container with fast access possibilities AND insertion order preserving capability is needed. Boost's multi_index_container helps (see here for more): Use a sequenced index together with oder indizes of your choice.

Example: creating a lookup table for flags and full names

f → fleetid

t → timestamp…

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
namespace bmi = boost::multi_index;
struct FlagInfo {
    std::string flag;       // eg. F
    std::string full_name;  // eg. fleetid
    FlagInfo(std::string f,std::string n):flag(f),full_name(n) {}
struct flag{}; // to access the tag
/** a map/list hybridcontainer preserving insertion order and indexing by flag*/
typedef bmi::multi_index_container<
        bmi::ordered_unique< bmi::tag<flag>,  BOOST_MULTI_INDEX_MEMBER(FlagInfo,std::string,flag)>
 > FlagList;
// map/list-like container
typedef FlagList::iterator FlagListIterator;

Insert some elements

FlagList flag_list;
flag_list.get<1>().insert(FlagInfo("o","orthdist")); // use index 1 of FlagInfo container
flag_list.get<1>().insert(FlagInfo("f","fleetid")); // use index 1 of FlagInfo container


FlagList::nth_index<1>::type::iterator itr = flag_list.get<1>().find(flag); // use first index
if (itr != flag_list.get<1>().end()) {
    cout << itr->full_name << endl;
cppcookbook.txt · Last modified: 2012/04/11 09:42 by mantis