C++ 标准库

C++ 常用的标准库

1. cmath

C数学库

常用函数描述
sin计算正弦
cos计算余弦
tan计算正切
acos计算反余弦
asin计算反正弦
atan计算反正切
atan2计算反正切with两个参数
cosh计算双曲余弦
sinh计算双曲正弦
tanh计算双曲正切
acosh计算反双曲余弦
asinh计算反双曲正弦
atanh计算反双曲正切
exp指数
log自然对数
log10以10为底的对数
modf将浮点数num分解成整数部分和小数部分
exp2以2为底的指数
log2以2为底的对数
powpow(float x, float y) 计算x的y次幂。
sqrt平方根
ceil求不小于x的最小整数
floor求不大于x的最达整数
fmod计算x/y的余数
trunc截断数字
round四舍五入
fabs浮点数的绝对值
abs整数的绝对值

2. 标准输入/输出流库:iostream

支持标准流cin、cout、cerr和clog的输入和输出,它还支持多字节字符标准流wcin、wcout、wcerr和wclog。

这里写图片描述

类名描述
ios_base数据流基础类
ios数据流基础类
istream输入数据流
ostream输出数据流
iostream输入/输出数据流
ifstream输入文件数据流
ofstream输出文件数据流
fstream输入/输出文件数据流
istringstream输入字符串数据流
ostringstream输出字符串数据流
stringstream输入/输出字符串数据流
streambuf数据流的基础缓冲类
filebuf文件数据流缓冲
stringbuf字符串数据流缓冲
对象描述
cin标准输入数据流
cout标准输出数据流
cerr标准错误输出数据流
clog标准日志输出数据流
类型描述
fpos数据流位置类模板
streamoff数据流offset类
streampos数据流位置类
操控器描述
boolalpha字母数字的布尔值
dec以十进制计数法形式显示整数变量
endl插入换行符并刷新
ends插入空字符
fixed使用固定的浮点计数法
flush刷新数据流缓冲区
hex以十六进制计数法形式显示整数变量
internal通过在内部位置插入字符来调整字段宽度
left导致宽度比指定输出宽度短的文本显示时靠左输出
nobooalpha转布尔值为0/1显示
noshowbase不显示进制前缀(如十六进制的’0x’)
noshowpoint仅显示浮点数(其小数部分为零)的整数部分
noshowpos不显示正数符号
noskipws输入流读取空格
nounitbuf缓冲区已满时缓冲和处理输出
nouppercase指定十六进制数字和科学计数法形式的指数以小写形式显示。
oct以八进制计数法形式显示整数变量
resetiosflags重置格式标志
right导致宽度比指定输出宽度短的文本显示时靠右输出
scientific使用科学记数法
setbase设置字段标志
setfill设置满字符
setiosflags设置格式标志
setprecision设置小数精度
setw设置字段宽度
showbase显示数字所采用的进制
showpoint显示浮点数的整数部分和小数点右侧的数字,即使小数部分为零
showpos正数显式带有符号
skipws输入流不读取空格
unitbuf在缓冲区未满时处理输出
uppercase指定十六进制数字和科学计数法形式的指数以大写形式显示
ws提取空格

3. algorithm

Non-modifying sequence operations

  • all_of : 判断是否范围内的所有元素都满足条件。
  • any_of : 判断是否范围内的所有元素中有一个满足条件。
  • none_of : 判断是否范围内的所有元素中没有一个满足条件。
  • for_each : 对指定范围内的每一个元素进行指定的操作。
  • find、find_if、find_if_not : 在指定范围中查找满足某个条件(值相等、条件满足、条件不满足)的元素。
  • find_end : 在指定序列中查找最后一个相等(或满足谓词条件)子序列
  • find_first_of : 在指定序列中查找第一个出现在另一个序列中(或满足谓词条件)的元素
  • adjacent_find : 在指定序列中查找第一个相等(值相等、满足条件)的元素对(2个元素)。
  • count、count_if : 对制定序列中的满足条件(值相等、满足条件)的元素进行计数。
  • mismatch : 给定两个元素序列,返回第一个不匹配(值不相等、不满足条件)的元素位置,以一个迭代器对指出。
  • equal : 判断两个序列是否相等(值相等、满足谓词条件)。
  • is_permutation : 判断是否一个序列是另一个序列的排列,即只有排列方式不相等(值不相等、不满足谓词条件)。
  • search、search_n : 在给定序列中查找子序列或者n个重复的元素序列

Mutating sequence operations

  • copy、copy_n、copy_if、copy_backward : 拷贝序列、拷贝序列中前n个元素、拷贝序列中满足条件的、从后往前拷贝序列。
  • move、move_backward移动序列、从后往前移动序列(移动后,任然可以对源序列进行操作,但元素值是未指定的)。
  • swap、iter_swap逐元素交换序列、交换两个序列。
  • transform : 对一个 序列进行变换并输出、对两个序列进行变换并输出(变换通过自定义谓词来实现)。
  • replace、replace_if、replace_copy、replace_copy_if : 替换满足条件(值相等、满足谓词条件)的元素为给定元素、替换满足条件的元素并将其拷贝至别处。
  • fill、fill_n : 将给定序列元素填充为给定值、 将给定的前n个元素填充为给定值。
  • generate、generate_n : 用自定义的生成器生成元素,并将这些元素赋值给给定序列或前n个序列。
  • remove、remove_if : 移除相等或满足谓词条件的元素。 注意,若有元素被移除,指向这些元素之后的迭代器的可以使用,但结果是未指定的(unspecified)
  • unique、unique_copy使序列唯一(即若有重复元素,保留第一个,其余全部移除)、是序列唯一并拷贝至目的地。
  • reverse、reverse_copy : 将给定序列逆转、将给定序列逆转并拷贝至目的地。
  • rotate、rotate_copy : 将给定序列左旋转(middle - first)个元素、将给定序列左旋转(middle - first)个元素并拷贝。
  • shuffle : 使用均匀随机数生成器将给定序列洗牌(即打乱,重新分布)。

下面几个函数有关分区的同一方面,但又功能却不想上面所列那么相似,故而分开叙述:

  • is_partition : 用给定的一元谓词判断给定序列是否被正确分区(即前一部分元素调用谓词返回true,后一部分返回false)。
  • partition : 对给定序列进行分区操作
  • stable_partition : 与partition操作相似,但是两个group(即分区成的两个分区)内元素的相关顺序保持不变(stable)
  • partition_copy : 与partition相似,但是两个分区group结果被拷贝到两个指定的位置
  • partition_point返回分区点,该点之前、该点之后(包括该点)分别为两个分区。

这些函数都有两个版本:使用operator < 的、使用函数子Compare的。

  • sort : 排序。
  • stable_sort : 稳定排序。
  • partial_sort : 部分排序,对于给定的序列,只排序前middle - first个元素,并将它们放置在[first, middle)范围中,剩余位置的元素顺序为指定。
  • partial_sort_copy : paartial_sort函数的copy版本。
  • is_sorted、is_sorted_util : 判断给定序列是否为已排序(使用operator < 或 自定义函数子判断)的。
  • nth_element : 将nth迭代器指定的位置排序为结果元素。(实际上应该是使用快排实现的)
  • lower_bound、upper_bound、equal_range : 返回下界、上界、相等性范围。
  • binary_search : 在给定序列中对元素进行二分查找。
  • merge、inplace_merge : 合并两个序列并输出。
  • includes : 判断是否一个序列重的所有元素都被包含在另一个序列中。
  • set_union并集
  • set_intersection交集
  • set_difference差集
  • set_symmetric_difference对称差集
  • push_heap : 将一个元素push进由序列表示的heap中,并维持堆得性质。
  • pop_heap : 将一个元素从heap中pop(实际上被交换到尾部)。
  • make_heap : 将给定序列构造成heap。
  • sort_heap : 对给定堆进行排序(可能有特殊的算法对堆排序进行优化)。
  • is_heap、is_heap_util : 判断给定序列是否为堆、判断给定序列到哪个位置之前为堆。
  • min、max : 返回最小值、最大值。
  • minmax : 返回pair
  • min_element、max_element : 返回序列中第一个最小值、最大值。
  • minmax_element : 返回pair
  • lexicographical_compare : 对两个序列进行字典序排序。
  • next_permutation、prev_permutation : 判断给定序列是否存在下一个或者上一个组合(所有可能的排列组合先由字典序排序,再进行判断)。

4. numeric

//accumulate 累加
template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init);

template <class InputIterator, class T, class BinaryOperation>
   T accumulate (InputIterator first, InputIterator last, T init,
                 BinaryOperation binary_op);
//示例:
int myfunction (int x, int y) {return x+2*y;}
struct myclass {
    int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
  int init = 100;
  int numbers[] = {10,20,30};

  std::cout << "using default accumulate: ";
  std::cout << std::accumulate(numbers,numbers+3,init);
  std::cout << '\n';

  std::cout << "using functional's minus: ";
  std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
  std::cout << '\n';

  std::cout << "using custom function: ";
  std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
  std::cout << '\n';

  std::cout << "using custom object: ";
  std::cout << std::accumulate (numbers, numbers+3, init, myobject);
  std::cout << '\n';

  return 0;
}
/*
using default accumulate: 160
using functional's minus: 40
using custom function: 220
using custom object: 280*/

//adjacent_difference计算相邻差值
#include <iostream>  
#include <functional>   
#include <numeric>    
int myop (int x, int y) {return x+y;}
int main () {
  int val[] = {1,2,3,5,9,11,12};
  int result[7];

  std::adjacent_difference (val, val+7, result);
  std::cout << "using default adjacent_difference: ";
  for (int i=0; i<7; i++) std::cout << result[i] << ' ';
  std::cout << '\n';

  std::adjacent_difference (val, val+7, result, std::multiplies<int>());
  std::cout << "using functional operation multiplies: ";
  for (int i=0; i<7; i++) std::cout << result[i] << ' ';
  std::cout << '\n';

  std::adjacent_difference (val, val+7, result, myop);
  std::cout << "using custom function: ";
  for (int i=0; i<7; i++) std::cout << result[i] << ' ';
  std::cout << '\n';
  return 0;
}
/*
using default adjacent_difference: 1 1 1 2 4 2 1
using functional operation multiplies: 1 2 6 15 45 99 132
using custom function: 1 3 5 8 14 20 23*/

//inner_product点积
int myaccumulator (int x, int y) {return x-y;}
int myproduct (int x, int y) {return x+y;}
int main () {
  int init = 100;
  int series1[] = {10,20,30};
  int series2[] = {1,2,3};

  std::cout << "using default inner_product: ";
  std::cout << std::inner_product(series1,series1+3,series2,init);
  std::cout << '\n';

  std::cout << "using functional operations: ";
  std::cout << std::inner_product(series1,series1+3,series2,init,
                                  std::minus<int>(),std::divides<int>());
  std::cout << '\n';

  std::cout << "using custom functions: ";
  std::cout << std::inner_product(series1,series1+3,series2,init,
                                  myaccumulator,myproduct);
  std::cout << '\n';

  return 0;
}
/*
using default inner_product: 240
using functional operations: 70
using custom functions: 34*/

// partial_sum 计算部分和
int myop (int x, int y) {return x+y+1;}
int main () {
  int val[] = {1,2,3,4,5};
  int result[5];

  std::partial_sum (val, val+5, result);
  std::cout << "using default partial_sum: ";
  for (int i=0; i<5; i++) std::cout << result[i] << ' ';
  std::cout << '\n';

  std::partial_sum (val, val+5, result, std::multiplies<int>());
  std::cout << "using functional operation multiplies: ";
  for (int i=0; i<5; i++) std::cout << result[i] << ' ';
  std::cout << '\n';

  std::partial_sum (val, val+5, result, myop);
  std::cout << "using custom function: ";
  for (int i=0; i<5; i++) std::cout << result[i] << ' ';
  std::cout << '\n';
  return 0;
}
/*
using default partial_sum: 1 3 6 10 15
using functional operation multiplies: 1 2 6 24 120
using custom function: 1 4 8 13 19*/

// iota 递增序列
int main () {
  int numbers[10];

  std::iota (numbers,numbers+10,100);

  std::cout << "numbers:";
  for (int& i:numbers) std::cout << ' ' << i;
  std::cout << '\n';

  return 0;
}
//numbers: 100 101 102 103 104 105 106 107 108 109

7. 容器相关

1. string

函数
1.stoi 将字符串转为整数
int stoi (const string&  str, size_t* idx = 0, int base = 10);
2.stol 将字符串转为long int
3.stoul 将字符串转为无符号整数
4.stoll 将字符串转为long long
5.stoull 将字符串转为 unsigned long long
6.stof 将字符串转为float浮点数
7.stod 将字符串转为double浮点数
8.stold 将字符串转为long double
9.to_string转换数值为字符串
  string to_string (int val);
  string to_string (long val);
  string to_string (long long val);
  string to_string (unsigned val);
  string to_string (unsigned long val);
  string to_string (unsigned long long val);
  string to_string (float val);
  string to_string (double val);
  string to_string (long double val);
类实例化:string
1. 成员函数
构造函数
string();
string (const string& str);
string (const string& str, size_t pos, size_t len = npos);
string (const char* s);
string (const char* s, size_t n);
string (size_t n, char c);
template <class InputIterator> string (InputIterator first, InputIterator last);
string (initializer_list<char> il);
string (string&& str) noexcept
//构造示例
std::string s0 ("Initial string");
//如上描述的几种方式
std::string s1;
std::string s2 (s0);
std::string s3 (s0, 8, 3);
std::string s4 ("A character sequence");
std::string s5 ("Another character sequence", 12);
std::string s6a (10, 'x');
std::string s6b (10, 42);      // 42 is the ASCII code for '*'
std::string s7 (s0.begin(), s0.begin()+7);
/*
Output:
s1: 
s2: Initial string
s3: str
s4: A character sequence
s5: Another char
s6a: xxxxxxxxxx
s6b: **********
s7: Initial
*/
operator=
string& operator= (const string& str);
string& operator= (const char* s);
string& operator= (char c);
string& operator= (initializer_list<char> il);
string& operator= (string&& str) noexcept;
//operator=使用示例
std::string str1, str2, str3;
str1 = "Test string: ";   // c-string
str2 = 'x';               // single character
str3 = str1 + str2;
迭代器

begin 字符串开始的迭代器 end 字符串结束的迭代器

rbegin 字符串逆序开始的迭代器 rend 字符串逆序结束的迭代器

cbegin 字符串开始的const_iiterator cend 字符串结束的const_iiterator

crbegin 字符串逆序开始的const_iiterator crend 字符串逆序结束的const_iiterator

容量

size 字符串长度 length
max_size 字符串最大长度

//resize
void resize (size_t n);
void resize (size_t n, char c);
//示例
std::string str ("I like to code in C");
std::cout << str << '\n';
unsigned sz = str.size();
str.resize (sz+2,'+');
std::cout << str << '\n';
str.resize (14);
std::cout << str << '\n';
/*
I like to code in C
I like to code in C++
I like to code
*/

clear 清空字符串
empty 判断字符串是否是空的

元素访问
//operator[] 
for (int i=0; i<str.length(); ++i)
    std::cout << str[i];
//at
for (unsigned i=0; i<str.length(); ++i)
    std::cout << str.at(i);
//back 字符串最后一个字符的引用
str.back() = '!';
//front 字符串第一个字符的引用
str.front() = 'T';
字符串编辑
//添加
/*operator+=
1.string& operator+= (const string& str);   
2.string& operator+= (const char* s);
3.string& operator+= (char c);*/
std::string name ("John");
std::string family ("Smith");
name += " K. ";   
name += family;        
name += '\n'; 
/*append
1.string& append (const string& str);
2.string& append (const string& str, size_t subpos, size_t sublen);
3.string& append (const char* s);
4.ring& append (const char* s, size_t n);
5.string& append (size_t n, char c);
6.template <class InputIterator>
string& append (InputIterator first, InputIterator last);
*/
str.append(str2);                   
str.append(str3,6,3);  
str.append("here: "); 
str.append("dots are cool",5);                         
str.append(10u,'.');                    
str.append(str3.begin()+8,str3.end());  
/*push_back
void push_back (char c);*/
str.push_back('s');
/*insert
1.string& insert (size_t pos, const string& str);
2.string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
3.string& insert (size_t pos, const char* s);
4.string& insert (size_t pos, const char* s, size_t n);
5.string& insert (size_t pos,   size_t n, char c);
6.iterator insert (const_iterator p, size_t n, char c); 
7.iterator insert (const_iterator p, char c);
8.template <class InputIterator>
iterator insert (iterator p, InputIterator first, InputIterator last);
9.string& insert (const_iterator p, initializer_list<char> il);
*/
str.insert(6,str2);                
str.insert(6,str3,3,4);     
str.insert(10,"to be ");     
str.insert(10,"that is cool",8);        
str.insert(15,1,':');              
it = str.insert(str.begin()+5,','); 
str.insert (str.end(),3,'.');       
str.insert (it+2,str3.begin(),str3.begin()+3);
/*assign
1.string& assign (const string& str);
2.string& assign (const string& str, size_t subpos, size_t sublen);
3.string& assign (const char* s);
4.string& assign (const char* s, size_t n);
5.string& assign (size_t n, char c);    
6.template <class InputIterator>
   string& assign (InputIterator first, InputIterator last);
7.string& assign (initializer_list<char> il);
8.string& assign (string&& str) noexcept;*/
std::string str;
std::string base="The quick brown fox jumps over a lazy dog.";
str.assign(base);
str.assign(base,10,9);   
str.assign("c-string");
str.assign("pangrams are cool",7);
str.assign(10,'*');
str.assign<int>(10,0x2D);      
str.assign(base.begin()+16,base.end()-12);
/*erase 删除部分字符串,减小长度
1.string& erase (size_t pos = 0, size_t len = npos);
2.iterator erase (const_iterator p);
3.iterator erase (const_iterator first, const_iterator last);*/
str.erase (10,8);                   
str.erase (str.begin()+9);           
str.erase (str.begin()+5, str.end()-9);
//void pop_back();删除最后一个字符
//void swap (string& str); 交换内容
/*replace 替换字符串pos开始长len的部分内容
1.string& replace (size_t pos,        size_t len,        const string& str);
  string& replace (const_iterator i1, const_iterator i2, const string& str);
2.string& replace (size_t pos,        size_t len,        const string& str,
                 size_t subpos, size_t sublen); 
3.string& replace (size_t pos,        size_t len,        const char* s);
  string& replace (const_iterator i1, const_iterator i2, const char* s);
4.string& replace (size_t pos,        size_t len,        const char* s, size_t n);
  string& replace (const_iterator i1, const_iterator i2, const char* s, size_t n);
5.string& replace (size_t pos,        size_t len,        size_t n, char c);
  string& replace (const_iterator i1, const_iterator i2, size_t n, char c);
6.template <class InputIterator>
  string& replace (const_iterator i1, const_iterator i2,
                   InputIterator first, InputIterator last);
7.string& replace (const_iterator i1, const_iterator i2, initializer_list<char> il);
*/
str.replace(9,5,str2);          
str.replace(19,6,str3,7,6);     
str.replace(8,10,"just a");    
str.replace(8,6,"a shorty",7); 
str.replace(22,1,3,'!');    
str.replace(str.begin(),str.end()-3,str3);  
str.replace(str.begin(),str.begin()+6,"replace");          
str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    
str.replace(str.begin()+12,str.end()-4,4,'o');     
str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
操作函数
//c_str 将字符串转为c-style字符串的数组,返回指向数组的const char*指针
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
//data  与c_str()类似,但是返回的数组不以空字符终止
//string类的查找函数: 
int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
//查找成功时返回所在位置,失败返回string::npos的值 
int rfind(char c, int pos = npos) const;//从pos开始从后向前查找字符c在当前串中的位置
int rfind(const char *s, int pos = npos) const;
int rfind(const char *s, int pos, int n = npos) const;
int rfind(const string &s,int pos = npos) const;
//从pos开始从后向前查找字符串s中前n个字符组成的字符串在当前串中的位置,成功返回所在位置,失败时返回string::npos的值 
int find_first_of(char c, int pos = 0) const;//从pos开始查找字符c第一次出现的位置
int find_first_of(const char *s, int pos = 0) const;
int find_first_of(const char *s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;
//从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置。查找失败返回string::npos 
int find_first_not_of(char c, int pos = 0) const;
int find_first_not_of(const char *s, int pos = 0) const;
int find_first_not_of(const char *s, int pos,int n) const;
int find_first_not_of(const string &s,int pos = 0) const;
//从当前串中查找第一个不在串s中的字符出现的位置,失败返回string::npos 
int find_last_of(char c, int pos = npos) const;
int find_last_of(const char *s, int pos = npos) const;
int find_last_of(const char *s, int pos, int n = npos) const;
int find_last_of(const string &s,int pos = npos) const; 
int find_last_not_of(char c, int pos = npos) const;
int find_last_not_of(const char *s, int pos = npos) const;
int find_last_not_of(const char *s, int pos, int n) const;
int find_last_not_of(const string &s,int pos = npos) const;
//find_last_of和find_last_not_of与find_first_of和find_first_not_of相似,只不过是从后向前查找
//size_t copy (char* s, size_t len, size_t pos = 0) const 复制子串给s
char buffer[20];
std::string str ("Test string...");
std::size_t length = str.copy(buffer,6,5);
//string substr (size_t pos = 0, size_t len = npos) const; 取子串
//compare:=0说明相等;<0说明被比较字符较大;>0说明被比较字符较小
int compare (const string& str) const noexcept;

int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;

int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;

int compare (size_t pos, size_t len, const char* s, size_t n) const;

2. valarray面向数值计算的数组

成员函数
构造函数
valarray( );
explicit valarray(size _ t _Count );
valarray( const Type& _Val , size _ t _Count );
valarray( const Type* _Ptr , size _ t _Count );
valarray( const slice _ array<Type>& _SliceArray );
valarray( const gslice _ array<Type>& _GsliceArray );
valarray( const mask _ array<Type>& _MaskArray );
valarray( const indirect _ array<Type>& _IndArray );
int init[]= {10,20,30,40};
std::valarray<int> first;                             // (empty)
std::valarray<int> second (5);                        // 0 0 0 0 0
std::valarray<int> third (10,3);                      // 10 10 10
std::valarray<int> fourth (init,4);                   // 10 20 30 40
std::valarray<int> fifth (fourth);                    // 10 20 30 40
std::valarray<int> sixth (fifth[std::slice(1,2,1)]);

1. apply 将 valarray 数组的每一个值都用 apply 所接受到的函数进行计算
2. cshift 将 valarray 数组的数据进行循环移动,参数为正者左移为负就右移
3. max 返回 valarray 数组的最大值
4. min 返回 valarray 数组的最小值
5. resize 重新设置 valarray 数组大小,并对其进行初始化
6. shift 将 valarray 数组移动,参数为正者左移,为负者右移,移动后由 0 填充剩余位
7. size 得到数组的大小
8. sum 数组求和
9. swap交换*this和x的内容 void swap (valarray& x) noexcept; 

重载的成员函数
valarray operator+() const;
valarray operator-() const;
valarray operator~() const;
valarray<bool> operator!() const;

valarray& operator*= (const valarray& rhs);
valarray& operator/= (const valarray& rhs);
valarray& operator%= (const valarray& rhs);
valarray& operator+= (const valarray& rhs);
valarray& operator-= (const valarray& rhs);
valarray& operator^= (const valarray& rhs);
valarray& operator&= (const valarray& rhs);
valarray& operator|= (const valarray& rhs);
valarray& operator<<= (const valarray& rhs);
valarray& operator>>= (const valarray& rhs);

valarray& operator*= (const T& val);
valarray& operator/= (const T& val);
valarray& operator%= (const T& val);
valarray& operator+= (const T& val);
valarray& operator-= (const T& val);
valarray& operator^= (const T& val);
valarray& operator&= (const T& val);
valarray& operator|= (const T& val);
valarray& operator<<= (const T& val);
valarray& operator>>= (const T& val);
non-member functions    
template <class T> valarray<T> operator* (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator* (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator* (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator/ (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator/ (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator/ (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator% (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator% (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator% (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator+ (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator+ (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator+ (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator- (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator- (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator- (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator^ (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator^ (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator^ (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator& (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator& (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator& (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator| (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator| (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator| (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator<< (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator<< (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator<< (const valarray<T>& lhs, const T& val);

template <class T> valarray<T> operator>> (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<T> operator>> (const T& val, const valarray<T>& rhs);
template <class T> valarray<T> operator>> (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator&& (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator&& (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator&& (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator|| (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator|| (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator|| (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator== (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator== (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator== (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator!= (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator!= (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator!= (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator< (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator< (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator< (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator> (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator> (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator> (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator<= (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator<= (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator<= (const valarray<T>& lhs, const T& val);

template <class T> valarray<bool> operator>= (const valarray<T>& lhs, const valarray<T>& rhs);
template <class T> valarray<bool> operator>= (const T& val, const valarray<T>& rhs);
template <class T> valarray<bool> operator>= (const valarray<T>& lhs, const T& val);

公共函数( 对数组的操作):

abs acos asin atan atan2 cos cosh exp log log10 pow sin sinh sqrt tan tanh

3. array静态空间数组

成员函数

**迭代器:**begin;end;rbegin;rend;cend;crbegin;crend

**容量:**size;max_size;empty
**元素访问:**operator[];at;front;back;data(返回指向对象第一个元素的指针)

fill void fill (const value_type& val) 给array对象填充元素

swap void swap (array& x) noexcept 交换

4.vector动态空间数组

成员函数

1.构造函数

std::vector<int> first;  //空vector                          
std::vector<int> second (4,100);  //  大小为4值为100的vector                
std::vector<int> third (second.begin(),second.end());  
std::vector<int> fourth (third);                       
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

迭代器:begin end rbegin rend cbegin cend crbegin crend

容量相关:size max_size resize capacity empty reserve

元素访问:operator[] at front back data

修改内容:

//assign
first.assign (7,100);             // 7 ints with a value of 100
std::vector<int>::iterator it;
it=first.begin()+1;
second.assign (it,first.end()-1); // the 5 central values of first
int myints[] = {1776,7,4};
third.assign (myints,myints+3); // assigning from array.
//push_back
myvector.push_back (元素);
//pop_back 删除最后一个元素
//insert
std::vector<int> myvector (3,100);
std::vector<int>::iterator it;
it = myvector.begin();
it = myvector.insert ( it , 200 );
myvector.insert (it,2,300);
it = myvector.begin(); // "it" no longer valid, get a new one:
std::vector<int> anothervector (2,400);
myvector.insert (it+2,anothervector.begin(),anothervector.end());
int myarray [] = { 501,502,503 };
myvector.insert (myvector.begin(), myarray, myarray+3);
//swap 与另一个vector交换
//erase
myvector.erase (myvector.begin()+5);
myvector.erase (myvector.begin(),myvector.begin()+3);
//clear 清空vector
//emplace:  myvector.emplace(迭代器位置,插入元素)
//emplace_back 末尾插入元素 myvector.emplace_back(元素)

5.list双向链表

1.构造函数

std::vector<int> first;  //空vector                          
std::vector<int> second (4,100);  //  大小为4值为100的vector                
std::vector<int> third (second.begin(),second.end());  
std::vector<int> fourth (third);                       
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

迭代器:begin end rbegin rend cbegin cend crbegin crend

容量相关:size max_size empty

元素访问: front back

修改内容:

//assign
first.assign (7,100);             // 7 ints with a value of 100
std::list<int>::iterator it;
it=first.begin()+1;
second.assign (it,first.end()-1); // the 5 central values of first
int myints[] = {1776,7,4};
third.assign (myints,myints+3); // assigning from array.
//push_back
mylist.push_back (元素);
//pop_back 删除最后一个元素
//insert
std::list<int> myvector (3,100);
std::list<int>::iterator it;
it = mylist.begin();
it = mylist.insert ( it , 200 );
mylist.insert (it,2,300);
it = mylist.begin(); // "it" no longer valid, get a new one:
std::list<int> anothervector (2,400);
mylist.insert (it+2,anothervector.begin(),anothervector.end());
int myarray [] = { 501,502,503 };
mylist.insert (mylist.begin(), myarray, myarray+3);
//swap 与另一个list交换
//erase
mylist.erase (mylist.begin()+5);
mylist.erase (mylist.begin(),mylist.begin()+3);
//emplace_front:开始处插入mylist.emplace_front(插入元素)
//emplace_back 末尾插入元素 mylist.emplace_back(元素)
//push_front:在开始出插入元素
//pop_front:末尾插入元素

其余操作函数

//splice
//将x的所有元素都转移到容器中
void splice (const_iterator position, list& x);
void splice (const_iterator position, list&& x);
//将i指向的元素转移到容器中
void splice (const_iterator position, list& x, const_iterator i);
void splice (const_iterator position, list&& x, const_iterator i);
//将x的[first,last]范围内元素转移到容器中
void splice (const_iterator position, list& x,
             const_iterator first, const_iterator last);
void splice (const_iterator position, list&& x,
             const_iterator first, const_iterator last);
//remove移除指定的元素 mylist.remove(89);
//remove_if移除满足条件的元素  mylist.remove_if (is_odd()); 
//unique  移除重复元素
//merge 合并排序链表
first.merge(second); // (second is now empty)
first.merge(second,mycomparison);
//sort排序
mylist.sort();
mylist.sort(compare_nocase);
//reverse 反序
mylist.reverse();

6.deque双向队列

1.构造函数

std::deque<int> first;  //空vector                          
std::deque<int> second (4,100);  //  大小为4值为100的vector                
std::deque<int> third (second.begin(),second.end());  
std::deque<int> fourth (third);                       
int myints[] = {16,2,77,29};
std::deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) )

迭代器:begin end rbegin rend cbegin cend crbegin crend

容量相关:size max_size resize empty

元素访问:operator[] at front back

修改内容:

//assign
first.assign (7,100);             // 7 ints with a value of 100
std::deque<int>::iterator it;
it=first.begin()+1;
second.assign (it,first.end()-1); // the 5 central values of first
int myints[] = {1776,7,4};
third.assign (myints,myints+3); // assigning from array.
//push_back 末尾插入元素
mydeque.push_back (元素);
//push_front 头部插入元素
//pop_back 删除最后一个元素
//pop_front 删除第一个元素
//insert
std::deque<int> myvector (3,100);
std::deque<int>::iterator it;
it = mydeque.begin();
it = mydeque.insert ( it , 200 );
mydeque.insert (it,2,300);
it = mydeque.begin(); // "it" no longer valid, get a new one:
std::deque<int> anothervector (2,400);
mydeque.insert (it+2,anothervector.begin(),anothervector.end());
int myarray [] = { 501,502,503 };
mydeque.insert (mydeque.begin(), myarray, myarray+3);
//swap 与另一个deque交换
//erase
myvector.erase (myvector.begin()+5);
myvector.erase (myvector.begin(),myvector.begin()+3);
//clear 清空deque
//emplace:  mydeque.emplace(迭代器位置,插入元素)
//emplace_front 头部插入元素 mydeque.emplace_back(元素)
//emplace_back 末尾插入元素 mydeque.emplace_back(元素)

7.\

bool fncomp (int lhs, int rhs) {return lhs<rhs;}
struct classcomp {
  bool operator() (const int& lhs, const int& rhs) const
  {return lhs<rhs;}
};
int main ()
{
  std::set<int> first;                           // 1
  int myints[]= {10,20,30,40,50};
  std::set<int> second (myints,myints+5);        // 2
  std::set<int> third (second);                  // 3
  std::set<int> fourth (second.begin(), second.end());  //4
  std::set<int,classcomp> fifth;                 //5
  bool(*fn_pt)(int,int) = fncomp;
  std::set<int,bool(*)(int,int)> sixth (fn_pt);  // 6 
  return 0;
}

迭代器:begin end rbegin rend cbegin cend crbegin crend

容量相关:size max_size resize empty

元素访问:operator[] at front back

修改内容:

//insert
 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;
 for (int i=1; i<=5; ++i) myset.insert(i*10);    
 ret = myset.insert(20);     //1         
 if (ret.second==false) it=ret.first;  
 myset.insert (it,25);    //2            
 myset.insert (it,24);            
 myset.insert (it,26);                
 int myints[]= {5,10,15};             
 myset.insert (myints,myints+3);//3
//swap 与另一个set交换
//erase
it = myset.begin();
++it;                                         // "it" points now to 20
myset.erase (it);//1
myset.erase (40);//2
it = myset.find (60);
myset.erase (it, myset.end());//3
//clear 清空deque
//emplace:  mydeque.emplace(插入元素)

其他操作函数

//find  查找指定元素,返回iterator
it=myset.find(20);
myset.erase (it);
myset.erase (myset.find(40));
//count 指定元素的计数  myset.count(i)
//lower_bound upper_bound
itlow=myset.lower_bound (30);       
itup=myset.upper_bound (60);  
 myset.erase(itlow,itup);
//equal_range  指定元素的范围
std::pair<std::set<int>::const_iterator,std::set<int>::const_iterator> ret;
ret = myset.equal_range(30);

multiset特性及用法和set完全相同,唯一的差别在于它允许键值重复。

8.map

map类
//map类声明模板
template <class Key, class T,  //键和值的类型
       class Compare = less<Key>,//键的比较方法
       class Alloc = allocator<pair<const               Key,T> >> class map;
//创建map类对象
1. explicit map (const key_compare& comp = key_compare(),const allocator_type& alloc = allocator_type());
   explicit map (const allocator_type& alloc);
2. template <class InputIterator>
   map (InputIterator first, InputIterator last,const key_compare& comp = key_compare(),
const allocator_type& = allocator_type());
3. map (const map& x);
   map (const map& x, const allocator_type& alloc); 
4. map (map&& x);
   map (map&& x, const allocator_type& alloc);
5. map (initializer_list<value_type> il,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());
//创建对象示例
bool fncomp (char lhs, char rhs) {return lhs<rhs;}
struct classcomp {
  bool operator() (const char& lhs, const char& rhs) const
  {return lhs<rhs;}
};
int main ()
{
  map<char,int> first;
  first['a']=10;
  first['b']=30;
  first['c']=50;
  first['d']=70;
  map<char,int> second (first.begin(),first.end());
  map<char,int> third (second);
  map<char,int,classcomp> fourth;        
  bool(*fn_pt)(char,char) = fncomp;
  map<char,int,bool(*)(char,char)> fifth (fn_pt); 

  return 0;
}
//重载赋值运算符
1. map& operator= (const map& x);
2. map& operator= (map&& x);
3. map& operator= (initializer_list<value_type> il);
//示例
int main ()
{
  map<char,int> first;
  map<char,int> second;

  first['x']=8;
  first['y']=16;
  first['z']=32;

  second=first;               
  first=map<char,int>(); 

  cout << "Size of first: " << first.size() << '\n';//0
  cout << "Size of second: " << second.size() << '\n';//3
  return 0;
}
迭代器:begin end rbegin rend cbegin cend crbegin crend
容量相关:size max_size empty
元素访问:operator[] at
修改内容:
//insert
  std::map<char,int> mymap;

  // first insert:
  mymap.insert ( std::pair<char,int>('a',100) );
  mymap.insert ( std::pair<char,int>('z',200) );

  std::pair<std::map<char,int>::iterator,bool> ret;
  ret = mymap.insert ( std::pair<char,int>('z',500) );
  if (ret.second==false) {
    std::cout << "element 'z' already existed";
    std::cout << " with a value of " << ret.first->second << '\n';
  }
  // second insert:
  std::map<char,int>::iterator it = mymap.begin();
  mymap.insert (it, std::pair<char,int>('b',300));  
  mymap.insert (it, std::pair<char,int>('c',400));  
  // third insert:
  std::map<char,int> anothermap;
  anothermap.insert(mymap.begin(),mymap.find('c'));
//swap 与另一个map交换 map1.swap(map2)
//erase
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;
  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;
  mymap['d']=40;
  mymap['e']=50;
  mymap['f']=60;
  it=mymap.find('b');
  mymap.erase (it);    //1 删除指定迭代器
  mymap.erase ('c');                  //2 删除指定 key
  it=mymap.find ('e');
  mymap.erase ( it, mymap.end() ); // 3 删除指定范围
//clear 清空map
//emplace: 插入元素,mymap.emplace('x',100);
observers
//key_comp
  std::map<char,int> mymap;
  std::map<char,int>::key_compare mycomp = mymap.key_comp();
  mymap['a']=100;
  mymap['b']=200;
  mymap['c']=300;
  char highest = mymap.rbegin()->first;    
  std::map<char,int>::iterator it = mymap.begin();
  do {
    std::cout << it->first << " => " << it->second << '\n';
  } while ( mycomp((*it++).first, highest) );
//value_comp
  std::map<char,int> mymap;
  mymap['x']=1001;
  mymap['y']=2002;
  mymap['z']=3003;
  std::pair<char,int> highest = *mymap.rbegin(); 
  std::map<char,int>::iterator it = mymap.begin();
  do {
    std::cout << it->first << " => " << it->second << '\n';
  } while ( mymap.value_comp()(*it++, highest) );
其他操作函数
//find  查找指定key,返回iterator
it = mymap.find('b');
//count 指定key的计数  mymap.count(某个键值)
//lower_bound upper_bound
itlow=mymap.lower_bound (某个键值);       
itup=mymap.upper_bound (某个键值);  
mymap.erase(itlow,itup);
//equal_range  指定key的范围
std::pair<std::map<int>::const_iterator,std::map<int>::const_iterator> ret;
ret = mymap.equal_range(某个键值);
multimap类

multimap特性以及用法与map完全相同,唯一的差别在于: 允许重复键值的元素插入容器:键值key与元素value的映照关系是多对多的关系 ;没有定义[]操作运算

9.queue

queue
创建FIFO队列对象
std::deque<int> mydeck (3,100);   
std::list<int> mylist (2,200);  

std::queue<int> first;                 //1
std::queue<int> second (mydeck);       // 2

  std::queue<int,std::list<int> > third; // 3
  std::queue<int,std::list<int> > fourth (mylist);//4
成员函数
//empty  myqueue.empty()
//size  myqueue.size()
//front  队首元素的引用 myqueue.front()
//back  队尾元素的引用 myqueue.back()
//push 插入元素
//pop 弹出栈顶元素
//swap 交换两个栈的内容
//emplace 插入新元素
priority_queue类似于堆
创建对象
#include <functional>     // std::greater

class mycomparison
{
  bool reverse;
  public:
      mycomparison(const bool& revparam=false)
      {reverse=revparam;}
      bool operator() (const int& lhs, const int&rhs) const       {
           if (reverse) return (lhs>rhs);
           else return (lhs<rhs);
      }
};
int main ()
{
  int myints[]= {10,60,50,20};

  std::priority_queue<int> first;//1 
  std::priority_queue<int> second (myints,myints+4);//2 
  std::priority_queue<int, std::vector<int>,   std::greater<int> >third (myints,myints+4);//3  小顶堆
  typedef std::priority_queue<int,std::vector<int>,mycomparison> mypq_type;

  mypq_type fourth;                 // 4 大顶堆
  mypq_type fifth (mycomparison(true)); //5 小顶堆
成员函数:empty size top push pop swap emplace

10.stack

创建stack对象
std::deque<int> mydeque (3,100);  
std::vector<int> myvector (2,200);    

std::stack<int> first;                    //1 空对象
std::stack<int> second (mydeque);         //2 用队列创建

std::stack<int,std::vector<int> > third;  //3 空对象
//4 用vector创建
std::stack<int,std::vector<int> > fourth (myvector);
成员函数
//empty  mystack.empty()
//size  mystack.size()
//top  栈顶元素的引用 mystack.top()
//push 插入元素
//pop 弹出栈顶元素
//swap 交换两个栈的内容
//emplace 插入新元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值