<algorithm>
std::sort
std::reverse
std::swap
std::move
std::count_if
std::min
std::max
std::min_element
std::max_element
std::accumulate
<numeric>
std::iota
<string>
std::to_string
<bitset>
std::bitset
Monday, July 31, 2017
Convert case in C / C++
Sunday, July 30, 2017
Friday, July 28, 2017
Bitwise operations in C
& bitwise AND
| bitwise inclusive OR
^ bitwise XOR (eXclusive OR)
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)
Masking operation:
To get the k-th bit of number n,
(n & ( 1 << k )) >> k
or
int mask = 1 << k;
int masked_n = n & mask;
int thebit = masked_n >> k;
Swap two variables without a temporary variable:
int x = 10, y = 5;
Method 1. XOR
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
note: XOR is both commutative and associative
| bitwise inclusive OR
^ bitwise XOR (eXclusive OR)
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)
Masking operation:
To get the k-th bit of number n,
(n & ( 1 << k )) >> k
or
int mask = 1 << k;
int masked_n = n & mask;
int thebit = masked_n >> k;
Swap two variables without a temporary variable:
int x = 10, y = 5;
Method 1. XOR
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
y = (x^y)^y = x^(y^y) = x^0 = x
x = (x^y)^(x^y)^y = x^y^x = y
Method 2. arithmetic // may cause overflow
// Code to swap 'x' and 'y'
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
Method 2. arithmetic // may cause overflow
// Code to swap 'x' and 'y'
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
Subscribe to:
Posts (Atom)