Monday, April 13, 2015

Overview

From vectors to maps to output streams, the C++ standard library has everything you want or need. This post will contain small snippets of different classes that you can find in the std. You can find more documentation here.

Content

Vector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <vector>

std::vector<int> v;
v.push_back(3);   // [3]
v.push_back(6);   // [3,6]
v.pop_back();     // [3]
v.push_back(7);   // [3,7]
v.push_back(9);   // [3,7,9]
std::cout << v[2] // 7

// Deletes the second element (g[1])
std::vector<int> g = {2,5,8,11,14};
g.erase(g.begin() + 1); // [2,8,11,14]

// Deletes the 2nd through 3rd elements (vec[1], vec[2])
g.erase(g.begin() + 1, g.begin() + 3);

// size
std::vector<int>::size_type size=3;

// iterator
for(std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
    /* std::cout << *it; ... */
}

// reverse iterator
for (std::vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it) {
    // std::cout << *it; ...
}

// Ranged for-loop
for (const auto& item : g) {
    // std::cout << item; ....
}

// indecies
for(std::vector<int>::size_type i = 0; i != v.size(); i++) {
    /* std::cout << someVector[i]; ... */
}

Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <map>
//Map is a balanced BST

// or std::map<string, int> m = { {"first", 1}, {"second", 2}, {"third", 3} };
std::map<string, int> m;

m["first"] = 1;
m["second"] = 2;
m["third"] = 3;

std::pair<string,int> p("forth", 4);
m.insert(p); // { "first":1, "second":2, "third":3, "forth":4 }

// auto = std::pair<string,int>::iterator
for (auto it = m.begin(); it != m.end(); ++it) {
    std::cout << it->first << " " << it->second << std::endl;
}
/*
first 1
second 2
third 3
forth 4
*/

int forth = m["forth"];
// forth = 4

// it is an iterator that points to the pair whose key is "second"
// the find method runs in O(log n) time since it's a BST
auto it = mymap.find("second");
m.erase(it);        // { "first":1, "third":3, "forth":4 }
m.erase("forth");   // { "first":1, "third":3 }

Set

1
2
3
4
5
6
7
8
9
10
11
12
#include <set> 

// or std::set<std::string> s = {"first", "second", "third", "forth"};
std::set<std::string> s;
s.insert("first");
s.insert("second");
s.insert("third");
s.insert("forth");

auto it = s.find("second");
s.erase(it);        // { "first", "third", "forth" }
s.erase("forth");   // { "first", "third" }

Tuple

1
2
3
4
5
auto my_tuple = std::make_tuple(5, 6, 7);

std::cout << std::get<0>(my_tuple); // 5
std::cout << std::get<1>(my_tuple); // 6
std::cout << std::get<2>(my_tuple); // 7

Random Posts