Skip to content

Instantly share code, notes, and snippets.

@rubienr
Last active October 5, 2022 22:20
Show Gist options
  • Save rubienr/c8c940890ca7685d727312a256eb958c to your computer and use it in GitHub Desktop.
Save rubienr/c8c940890ca7685d727312a256eb958c to your computer and use it in GitHub Desktop.
C++ Cheat Sheet

C++ Cheat Sheet

Collections

collection decision tree collection decision tree more details

cXX

Boost

Vector Insert/Iterate Example

    std::vector<int> vect(10);

    int cnt = 0;
    for (std::vector<int>::iterator iter = vect.begin(); iter != vect.end(); iter++) {
        (*iter) = cnt++;
    }


    for (std::vector<int>::reverse_iterator iter =  vect.rbegin(); iter != vect.rend(); iter++) {
        cout << "iter: " << (*iter) << endl;
    }

Vector Sort Example

    std::vector<int> unsorted({32,71,12,45,26,80,53,33});
    std::sort(unsorted.begin(), unsorted.end());

    for ( int & value : unsorted) {
        cout << value << " ";
    }
    cout << endl;

Map Example

    std::map<int, char, std::greater<int>> mymap;

    for (int idx = 'a'; idx <= 'z'; idx++ ) {
        mymap[idx] = idx;
    }

    for (std::pair<int, char> keyvalue : mymap) {
        cout << "key: " << keyvalue.first << " value: " << keyvalue.second << endl;
    }

Move Example

class MyMove {

private:
    int x;
public:
    MyMove() : x(42) { }

    MyMove(MyMove &&o) : x(std::move(o.x)) {
        cout << "moved " << endl;
    }

    MyMove(MyMove &o) : x(std::move(o.x)) {
        cout << "copied" << endl;
    }

private:
    MyMove &operator=(const MyMove &) {
        cout << "assigned" << endl;
    }
};

// ------------

    MyMove a;
    MyMove b = std::move(a);

Template Example

template<class MyType>
MyType &myTemplateFunction(MyType e) {
    cout << "template func: type " << typeid(MyType).name() << " value " << e << endl;
}


template<class MyType>
class TClass {

public:
    void print(MyType e) {
        cout << "template class: type " << typeid(MyType).name() << " value " << e << endl;
    }
};

Stream Operator Overloading (global)

std::ostream &operator<<(std::ostream &out, const FooBase &o) {
    out << "op overloading: <<" << o.getId() << ">>" << endl;
    return out;
}

File Read Example

    std::fstream inFile("~/ClionProjects/recap-cpp/main.cpp");
    std::string line;
    while (std::getline(inFile, line)) {
        cout << "-------->" << line << "<---------" << endl;
    }

File Write Example

    std::ofstream outFile("~/ClionProjects/recap-cpp/tmp.txt", std::fstream::out | std::fstream::trunc);
    std::ostream& out = outFile;
    out << "foo test bla" << endl << std::flush;
    outFile.close();

Related Pages

http://www.cheat-sheets.org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment