Neither one nor Many

 
July 16 2016

C++ streams

i.e.;

 std::ifstream fi;
 fi.open("all.csv");
 std::string line;
 while (getline(fi, line, '\n')) {
     std::cout << "line = " << line << std::endl;
 }

writing:

#include <fstream>
std::ofstream log_file(
    "log_file.txt", std::ios_base::out | std::ios_base::app );
log_file << text << std::endl;

vector

Initialize N elements at once with: vector<int> vec_out(vec_in.size(), 0);.

Put last elem in front data[0] = data[data.size() - 1]; and erase last data.erase(data.begin() + (data.size() - 1), data.end());

algorithms

Sum accumulate(count.begin(), count.end(), 0).

Rotate 1 2 3 -> 2 3 1 with rotate(A.begin(), A.begin() + K, A.end());, the other way around with rbegin() and rend() respectively.

Find std::find(std::begin(c), std::end(c), 1001) != std::end(c);

Erase + remove idiom: c.erase(std::remove(std::begin(c), std::end(c), 1001), std::end(c));

std::transform

std::vector<Foo> foos;
for (int i = 0; i<10; i++) {
    foos.push_back(Foo(i));
}

std::vector<int> xs;
xs.resize(foos.size());
std::transform(foos.begin(), foos.end(), xs.begin(), [](Foo f){return f.x;});

from: https://stackoverflow.com/questions/39844106/extract-elements-from-a-vector-of-object

with ranges:

#include <iostream>
#include <range/v3/view.hpp>

struct Object {
    int x;
    float y;
};

int main() {
    std::vector<Object> objs = {{1, 4.2f}, {42, 5.1f}, {69, 6.9f}};
    std::vector<int> xs = objs | ranges::view::transform(&Object::x);
    for (auto x : xs) {
        std::cout << " " << x;
    }
    std::cout << std::endl;

    for (auto y : objs | ranges::view::transform(&Object::y)) { // No new vector created.
        std::cout << " " << y;
    }
    std::cout << std::endl;
}

join string boost so

#include <boost/algorithm/string/join.hpp>
#include <vector>
#include <iostream>

int main(int, char **)
{
    std::vector<std::string> list;
    list.push_back("Hello");
    list.push_back("World!");

    std::string joined = boost::algorithm::join(list, ", ");
    std::cout << joined << std::endl;
}

join string non-boost

std::string s = std::accumulate(std::next(v.begin()), v.end(),
                                std::to_string(v[0]), // start with first element
                                [](std::string a, int b) {
                                    return a + '-' + std::to_string(b);
                                });

Templates

Forwarding

template <typename... Params>
void remove(Params &&... node) {
  static_assert(std::is_constructible<Type, Params...>::value, "parameters are invalid for constructing a Type");
  auto n = std::make_unique<value_type >(std::forward<Params>(node)...);
  remove(static_cast<const value_type &>(*n.get()));
}

stringstream

#include <sstream>
stringstream ss;
ss << "hello world" << 123 << endl;
ss.str(); // ...
ss.clear();
ss.str("");  // re-use.

binary search

std::sort (v.begin(), v.end());                       // 10 10 10 20 20 20 30 30
auto low = std::lower_bound (v.begin(), v.end(), 20); //          ^        ^
auto up  = std::upper_bound (v.begin(), v.end(), 20); //                   ^

priority_queue

// "if the number is less.. goes down the pile"
priority_queue<int, vector<int>, std::less<int>> pq; 
for (int i : {1, 6, 3}) 
    pq.emplace(i);
pq.top(); // 6
pq.pop();
pq.top(); // 3

Exposes it's container as protected member variable. In order to access, you have to extend priority_queue. Underlying data structure is a heap.

bitsets

bitset<8> bs; 
bs.set(0);
bs.set(2); // 00000101

set

Underlying container type is a binary tree. So most stuff is log n. Note that a binary tree is also sorted, so the first element *the_set.cbegin() is the min() element!

memory

unique_ptr<foo> p{nullptr};
p = make_unique<foo>();

Perfect forwarding variable template args

namespace std {
  template<typename T, typename ...Args>
  std::unique_ptr<T> make_unique(Args &&...args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  }
}

limits

std::numeric_limits<size_t>::max();

ostream_iterator

#include <iterator>
copy(tokens.begin(), tokens.end(), ostream_iterator<string>(cout, "\n"));

readable input parameters

void split(string in, vector<string> *tokens_ptr, string delim = " ") {
    vector<string> &tokens = *tokens_ptr;
    ...

split(input, &tokens, " ");

string

// find
string s("aa b c");
s.find(" "); // finds 2
s.find(" ", 3); // finds 4 (starting search from the "b")
// substr()
s.substr(0, 2); // start + length!
s.substr(pos, pos - previous); // typical

tokenizer with getline()

really nice implementation using getline() from this stackoverflow answer.

#include <string>
#include <sstream>
#include <vector>

using namespace std;

void split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}


vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

iterate to stdout with ostream_iterator<T> and copy()

#include <iterator>
#include <algorithm>

// output even a newline after each element
copy(c.begin(), c.end(), ostream_iterator<string>(cout, "\n"));

convert binary file into c code

xxd -i favicon.ico > favicon.ico.h

sorting concatinating

template <typename T>
std::string join_keys(std::vector<T> &idsVec) {
    std::stringstream ids;

    // remove dupes
    std::sort(idsVec.begin(), idsVec.end());
    idsVec.erase(std::unique(idsVec.begin(), idsVec.end() ), idsVec.end());

    // join ids with ","
    std::copy(idsVec.begin(), idsVec.end(), std::ostream_iterator<T>(ids, ","));
    std::string ids_str = ids.str();

    // remove the trailing ", "
    ids_str.erase(ids_str.empty() ? 0 : ids_str.length() - 1);
    return ids_str;
};

optional

c++17 will support it, in g++ version 7.0 it can be enabled with --std=c++1z

#include <optional>

...
std::optional<std::string> empty;
std::optional<std::string> filled{"hello"};

if (filled) {
    std::cout << "filled = " << *filled << std::endl;
}   
std::cout << "empty = " << empty.value_or("nothing") << std::endl;

c++14 flag --std=c++1y in g++ 4.9 supports std::experimental::optional

#include <experimental/optional>

...
std::experimental::optional<int> empty;

Note there is also make_optional.

file reading

using namespace std;
ifstream ifile("webroot/"s + folder + "/" + file, ios::binary);
string s( (istreambuf_iterator<char>(ifile)),
          (istreambuf_iterator<char>()) );
cout << "read = " << s.size() << " & " << s.length() << endl;

multiline string literal

const char * long_test = R"( ... )";
const char * long_test = R"XXX( ... )XXX";

std::experimental::optional and std::reference_wrapper

Passing optional reference:

#include <iostream>
#include <experimental/optional>
#include <functional>

namespace std {
  using std::experimental::optional;
}

void foo(std::optional<std::reference_wrapper<bool>> flag = {}) {
    if (flag) {
        flag->get() = true;
    }
}

int main() {
    bool flag = false;
    foo({flag});
    std::cout << "flag is now: " << std::boolalpha << flag << std::endl;
}

chrono stuff

/* sleeping */
std::this_thread::sleep_for(std::chrono::milliseconds(1000));

/* timing */
auto last_received = std::chrono::high_resolution_clock::now();
...
auto current_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> idle = current_time - last_received;
if (idle.count() > 500.) {

    /* literals */
    using namespace std::literals;

    std::this_thread::sleep_for(0.5s);

}

back_inserter

#include <algorithm> // copy
#include <iterator> // back_inserter
std::copy(from_vector.begin(), from_vector.end(), std::back_inserter(to_vector));

boost reverse iter

void OpenStackStrategy::apply(CustomizationFileEntryPairList &customizations)
{
  size_t index = customizations.size();
  for (const auto &customization : boost::adaptors::reverse(customizations)) {
    const auto &file = customization.first;
    const auto &entry  = customization.second;
    index--;

cout fu

std::cout.precision(17);
std::cout << std::fixed << some_double_variable << std::endl;
std::cout << std::boolalpha << some_boolean_variable << std::endl;

vector or set difference

std::sort(ignore_domains.begin(), ignore_domains.end());
std::sort(search_domains.begin(), search_domains.end());

std::vector<std::string> result;
std::set_difference(
        search_domains.begin(), search_domains.end(),
        ignore_domains.begin(), ignore_domains.end(),
        std::back_inserter( result )
);

source

epoch time

auto now = std::chrono::system_clock::now();
auto epoch = std::chrono::system_clock::to_time_t( now );
Cheatsheets Comments (0)


Leave a Reply

Comment may not be visible immediately, because I process everything manually.**

**) I plan to automate this.., but it's on my ToDo since for ever..


Author:
Ray Burgemeestre
february 23th, 1984

Topics:
C++, Linux, Webdev

Other interests:
Music, Art, Zen