C++C++
BeginnerLesson 7 of 18

std::string and std::vector – C++

The two most important standard types: text and dynamic arrays.

std::string manages text automatically – memory, length, copies. You can concatenate strings with +, compare them and work with them using methods.

#include <iostream>
#include <string>

int main() {
    std::string s = "C++ is awesome";
    std::cout << s.size() << '\n';           // 14
    std::cout << s.substr(0, 3) << '\n';     // C++
    std::cout << s.find("is") << '\n';    // 4
    s += "!";
    std::cout << s << '\n';

    std::string a = "Hello", b = "World";
    std::cout << a + " " + b << ' ' << (a < b) << '\n';   // Hello World 1
    std::cout << s[0] << s.front() << s.back() << '\n';   // CC!
}

std::vector<T> is the standard array: dynamically growing, contiguous in memory, fast. For almost all collections, it is the right choice.

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{5, 3, 8, 1};
    v.push_back(10);
    std::sort(v.begin(), v.end());
    for (int z : v) std::cout << z << ' ';            // 1 3 5 8 10
    std::cout << '\n' << v.size() << ' ' << v.front() << ' ' << v.back() << '\n';   // 5 1 10

    std::vector<int> nullen(4, 0);    // four zeros
    v.pop_back();                     // remove the last element
    v.at(0) = 99;                     // with bounds checking (throws an exception)
}
Tipstd::array<int, 5> is a fixed-size array (the size is fixed at compile time, no heap allocation). Use it instead of C arrays like int a[5], because it brings its size and iterators along.
Warningv[i] does not check whether i is valid – a wrong index is undefined behavior. v.at(i) throws std::out_of_range instead. After push_back, references and iterators to elements can become invalid (the vector relocates when needed).