
C++勉強一週目(4/19-4/26)
C++知識メモ
Modern C++ を読んで分からない・忘れやすい概念をまとめさせました
Reference VS Pointer
int x = 10;
int y = 20;
int* p = &x; //ポインタ
int& r = x; //参照(Reference)参照は別名、nullptr にできない。一度束縛したら別のオブジェクトに付け替えられない
ポインタは nullptr にできるし、別の対象に変更できる
Heap memory & Stack memory & Static storage
Heap memory
Dynamic allocation, for data which is not fixed at compile time
Stack memory
Mainly for local/temporary variables
Static storage
For object whose lifetime lasts for the entire program execution
# Heap memory
int* p = new int(42); // ヒープに確保
delete p; // 手動で解放する必要がある(smart ptrを使わないと)
# Stack memory
void f() {
int x = 10; //通常はstack memoryにありますが、Compilerの最適化でCpu Registerに位置することもある
}
# Static storage
int g = 10; // static storage duration
void f() {
static int count = 0; // also static storage duration
count++;
} std::find_if
戻り値は std::vector<int>::iterator
例
std::vector<int> v = {1, 3, 4, 8, 9};
auto it = std::find_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; });
if (it != v.end()) {
std::cout << "value = " << *it << '\n'; //値(4)
std::cout << "index = " << (it - v.begin()) << '\n'; //インデックス(2)
}std::lower_bound
ソート済み範囲において、指定された値「以上」の最初の要素を二分探索する。
戻り値は std::vector<int>::iterator
例
std::vector<int> v = {10, 20, 30, 40, 50};
auto it = std::lower_bound(v.begin(), v.end(), 25);
// it は 30 を指すLambda Function
[] はキャプチャ、() は引数、{} は処理本体
int x = 10;
auto add = [x](int y) {
return x + y;
};
std::cout << add(5) << '\n'; // 15LeetCode練習
10問ぐらい解けましたが、全部EAZYで特にメモすることがなく
来週計画
GWは用事あるので日本にいられない。。。