数据类型及运算

Mono-Awen / 2024-10-13 / 原文

数据类型

名称 字节 范围
char 1 (character or integer) 8 bits 有符号(signed): -128 ~ 127 无符号: 0 ~ 225
short 2 短整数 16 bits signed: -32768 ~ 32767 0 ~ 65535
long 4 长整数 32 bits signed: -2147483648 ~ 2147483647 0 ~ 4294967295
int 4 integer signed: -2147483648~2147483647 0~4294967295
float 浮点数 3.4e + / - 38 7 digits
double 8 双精度浮点数 15 digits
long double 8 15 digits
bool 1
wchar 2 bits 1wide characters

Declared constants (const)

const int width = 100;
const zip  = 120; //没有指定类型,编译器会假设为整形 int

条件运算符 Conditional Operator (?)

格式:

condition ? result1 : result2;

如果条件 condition 为 true 则返回 result1,否则将返回 result2

int a = 10, b = 5;
cout << (7 == 5) ? 4 : 3 << "\n";      // 返回3,因为7不等于5.
cout << (7 == 5) + 2 ? 4 : 3 << "\n";  // 返回4,因为7等于5+2.
cout << (5 > 3) ? a : b << "\n";       // 返回a,因为5大于3.
cout << (a > b) ? a : b << "\n";       // 返回较大值,a 或b.

位运算 Bitwise Operators

位运算符 Bitwise Operators ( &, |, ^, ~, <<, >> )

& And Logic AND
Or
^ Xor Logical exclusive OR
~ Not Complement to one (bit inversion)
<< Shl Shift Left
>> Shr Shift Right

运算符优先级

() [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid left to right
++ -- ~ ! sizeof new delete * & 指针和取地址 + - right to left
type 类型转换 right to left
.* ->* 指向成员的指针 left to right
* / % 乘、除、取模 left to right
+ - left to right
<< >> 位移 left to right
< > <= >= 关系操作符 left to right
== != 等于、不等于 left to right
& 按位与运算 left to right
^ 按位异或运算 left to right
按位或运算
&& 逻辑与运算 left to right
?: 条件运算 right to left
= *= /= %= += -= >>= <<= &= ^= = 赋值运算
, 逗号 left to right

字符串

#include <string>
string a;
int len = a.size(); //长度

字符串流

#include <string>
#include <sstream>

可对字符串的对象进行像流(stream)一样的操作

字符串转整数

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
signed main() {
  string mystr("1204");
  int myint;
  stringstream(mystr) >> myint;
  cout << myint;
}

输入的字符串包空格

getline(cin, YourStringName);

Inline 函数

inline 可放在函数声明之前。好处只对短小的函数有效,编译运行快一些

声明形式:

inline type name ( arguments… ) { instructions … }