Skip to content

This is a repository designed to facilitate learning C++ and enhance understanding of its fundamental concepts.

Notifications You must be signed in to change notification settings

iamstarlee/CXX-Tricks

Repository files navigation

11. decltype关键字

decltype关键字是C++11新标准引入的关键字,它和关键字auto的功能类似,也可以自动推导出给定表达式的类型,但它和auto的语法有些不同,auto推导的表达式放在“=”的右边,并作为auto所定义的变量的初始值,而decltype是和表达式结合在一起。

int i = 4;
decltype(i) a; //推导结果为int。a的类型为int。

10. 二维vector的最后一行

vector<vector<int>>& triangle
triangle.back()

9. C++中的pair

pair<ListNode*, ListNode*> results = f();
head = results.first;
tail = results.second;
//等价于
tie(head, tail) = f();
// 使用tie直接将结果更新到head和tail中[

8. 哈希表的遍历for(auto& count: counts)

如果没有&,每次遍历都会给重新开辟空间存放遍历的值,空间复杂度是O(n),而使用引用的话,即使用同一块空间。

7. int类型是32位,其最大值为啥是2的31次方减一

int类型是带符号整数,最高位是补码意义下的符号位,因此根据等比数列的求法:

$$ 2^0+2^1+2^2+...+2^{30} = {1 - 2*2^{30} \over (1-2)}=2^{31}-1 $$

6. this指针

在C++中,this指针指向对象的实例,每一个对象都可以通过this指针来访问自己的地址。友元函数没有this指针,因为友元不是类的成员,只有成员函数才有this指针。

5. std::iota in C++

void iota (ForwardIterator first, ForwardIterator last, T val);

Store increasing sequence, assign to every element in the range [first, last] successive values of val.

4. Convert string to integer

The C stdlib library atoi() function is used to convert a numeric string into integer value. Remember to convert string to char before using it.

string token;
atoi(token.c_str());

3. sort的lambda写法

std::sort(x, x + n,
          // Lambda expression begins
          [](float a, float b) {
              return (std::abs(a) < std::abs(b));
          } // end of lambda expression
        );

2. 二维vector的初始化

#define M 4
#define N 4

// one step, recommended
vector<vector<int>> matrix(M, vector<int>(N, 0));

1. C++ compilation in Ubuntu

g++ -o main main.cpp
./main

0. Cuda and Onnxruntime with C++ programming

About

This is a repository designed to facilitate learning C++ and enhance understanding of its fundamental concepts.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages