C++ Programming Keynotes

1. INT to string, char to string, string to char

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int a = 42; // int to string
string res = std::to_string(42); // it is a C++11 feature

stringstream ss; // int, char etc. to string
ss << a;
string res2 = ss.str();

char buffer[MAX]; // int to string
itoa(a, buffer); // itoa is not a C/C++ standard function
string res3 = string(buffer);

sprintf(buffer, "%d is %d", a, a); //int to string
string res4 = string(buffer);

int res5 = atoi(buffer); // string to int
// similar function: atol, atof, strtol

string str = "hello";
char* res5 = str.c_str(); // string to char*

char c = '1'; // one char to string
string res6 = string(1, c);

2. sort

1
2
vector<int> a; // a = {2, 4, 3, 6, 5};
std::sort(a.begin(), a.end());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* };
*/
struct customSort {
inline bool operator()(Interval& a, Interval& b){
return a.start < b.start;
}
};
vector<Interval>& intervals;
std::sort(intervals.begin(), intervals.end(), customSort());

3. ssh 中文远程乱码

1
2
3
4
sudo vim /etc/default/locale #change the file
LANG="en_US.UTF-8" # examples
LANGUAGE="en_US:en"
LC_ALL="zh_CN.UTF-8"

4. convertion

1
2
3
4
5
unsigned int aa = 6;
int bb = -20;
(aa+bb>6) ? cout << ">6\n" : cout << ">=6\n";
// unsigned int plus int --> unsigned int, aa + bb is unsigned int
// unless you explicit declare it as int, then the results will be -14