# C++常見函式庫
###### tags: `C/C++`
## C library
### <cmath>
1. double **pow (double base, double exponent)**;
Returns base raised to the power exponent: basee^exponent
2. double **sqrt (double x);**
Returns the square root of x.
開根號
```
#include <stdio.h> /* printf */
#include <math.h> /* sqrt */
int main ()
{
double param, result;
param = 1024.0;
result = sqrt (param);
printf ("sqrt(%f) = %f\n", param, result );
return 0;
}
Output:
sqrt(1024.000000) = 32.000000
```
3. double ceil (double x);
Rounds x upward, returning the smallest integral value that is not less than x.
```
#include <stdio.h> /* printf */
#include <math.h> /* ceil */
int main ()
{
printf ( "ceil of 2.3 is %.1f\n", ceil(2.3) );
printf ( "ceil of 3.8 is %.1f\n", ceil(3.8) );
printf ( "ceil of -2.3 is %.1f\n", ceil(-2.3) );
printf ( "ceil of -3.8 is %.1f\n", ceil(-3.8) );
return 0;
}
Output:
ceil of 2.3 is 3.0
ceil of 3.8 is 4.0
ceil of -2.3 is -2.0
ceil of -3.8 is -3.0
```
4. double floor (double x);
Rounds x downward, returning the largest integral value that is not greater than x.
### <cstdio>
1. int fprintf ( FILE * stream, const char * format, ... );
用於將一組字符寫入文件。它將格式化的輸出發送到流。
```
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
printf("Write to file : file.txt finished.");
}
```
2. int fscanf ( FILE * stream, const char * format, ... );
fscanf()函數用於從文件中讀取一組字符。它從文件讀取一個單詞,並在文件結尾返回EOF。
```
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
```
3. int **printf ( const char * format, ... )**;
Print formatted data to stdout
```
#include <stdio.h>
int main()
{
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000L);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
// printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
// printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
// printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
return 0;
}
Output:
Characters: a A
Decimals: 1977 650000
Preceding with blanks: 1977
Preceding with zeros: 0000001977
Some different radices: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick: 10
A string
```
4. int **scanf ( const char * format, ... )**;
Read formatted data from stdin
```
#include <stdio.h>
int main ()
{
char str [80];
int i;
printf ("Enter your family name: ");
scanf ("%79s",str); // up to 79 chars into str
printf ("Enter your age: ");
scanf ("%d",&i);
printf ("Mr. %s , %d years old.\n",str,i);
// printf ("Enter a hexadecimal number: ");
// scanf ("%x",&i);
// printf ("You have entered %#x (%d).\n",i,i);
return 0;
}
Enter your family name: Soulie
Enter your age: 29
Mr. Soulie , 29 years old.
Enter a hexadecimal number: ff
You have entered 0xff (255).
```
5. **char * gets ( char * str )**;
Get string from stdin
**gets可以接收空格**;
而scanf遇到空格、回车和Tab键都会认为输入结束,所以它不能接收空格。
But, 後來被fgets取代,因為gets有漏洞問題
**gets将不停地往s中塞东西,不管s的可用空间是否足够,就存在溢出漏洞问题**
```
#include <stdio.h>
int main()
{
char string [256];
printf ("Insert your full address: ");
gets (string); // warning: unsafe (see fgets instead)
printf ("Your address is: %s\n",string);
return 0;
}
```
6. int **puts ( const char * str )**;
Write string to stdout
**與printf差別:**
(1)puts的功能更单一,只能输出字符串,而printf可以根据给定的格式输出多种类型的数据
(2)puts()函数会自动在字符串末尾添加一个换行符,这意味着它会自动换行,而printf()函数没有此功能。
### <cstdlib>
1. double atof (const char* str);
Convert string to double
2. int **atoi (const char * str);**
Convert string to integer
3. double strtod (const char* str, char** endptr);
Convert string to double
```
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtod */
int main ()
{
char szOrbits[] = "365.24 29.53";
char* pEnd;
double d1, d2;
d1 = strtod (szOrbits, &pEnd);
d2 = strtod (pEnd, NULL);
printf ("The moon completes %.2f orbits per Earth year.\n", d1/d2);
return 0;
}
```
4. float strtof (const char* str, char** endptr);
Convert string to float
5. int rand (void);
Generate random number
```
v1 = rand() % 100; // v1 in the range 0 to 99
v2 = rand() % 100 + 1; // v2 in the range 1 to 100
v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
```
6. void* calloc (size_t num, size_t size);
Allocate and **zero-initialize array**
```
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* calloc, exit, free */
int main ()
{
int i,n;
int * pData;
printf ("Amount of numbers to be entered: ");
scanf ("%d",&i);
pData = (int*) calloc (i,sizeof(int));
if (pData==NULL) exit (1);
for (n=0;n<i;n++)
{
printf ("Enter number #%d: ",n+1);
scanf ("%d",&pData[n]);
}
printf ("You have entered: ");
for (n=0;n<i;n++) printf ("%d ",pData[n]);
free (pData);
return 0;
}
```
7. void* **malloc (size_t size)**;
Allocate memory block
Allocates a block of size bytes of memory, **returning a pointer to the beginning of the block.**
```
int *ptr = malloc(sizeof(int));
```
```
1、参数个数上的区别:
malloc函数:malloc(size_t size)函数有一个参数,即要分配的内存空间的大小。
calloc函数:calloc(size_t numElements,size_t sizeOfElement)有两个参数,分别为元素的数目和每个元素的大小,这两个参数的乘积就是要分配的内存空间的大小。
2、初始化内存空间上的区别:
malloc函数:不能初始化所分配的内存空间,在动态分配完内存后,里边数据是随机的垃圾数据。
calloc函数:能初始化所分配的内存空间,在动态分配完内存后,自动初始化该内存空间为零。
3、函数返回值上的区别:
malloc函数:函数返回值是一个对象。
calloc函数:函数返回值是一个数组。(array)
```
8. void* realloc (void* ptr, size_t size);
Reallocate memory block
Changes the size of the memory block pointed to by ptr.
ptr -- 這是以前用malloc,calloc或realloc分配,重新分配的內存塊的指針
size -- 這是新的內存塊的大小(以字節為單位)
9. void **free (void\* ptr);**
Deallocate memory block
10. int **abs (int n);**
Absolute value
Returns the absolute value of parameter n
### <cctype>
1. int isalnum ( int c );
Check if character is alphanumeric
Checks whether c is either a decimal digit or an uppercase or lowercase letter.
2. int isblank ( int c );
Check if character is blank
Checks whether c is a blank character.
The standard "C" locale considers blank characters the tab character ('\t') and the space character (' ').
3. int **isalpha ( int c );**
Check if character is alphabetic
Checks whether c is an alphabetic letter.
4. int **islower ( int c );**
Check if character is lowercase letter
Checks whether c is a lowercase letter.
5. int **isupper ( int c );**
Check if character is uppercase letter
Checks if parameter c is an uppercase alphabetic letter.
6. int **tolower ( int c );**
Convert uppercase letter to lowercase
Converts c to its lowercase equivalent if c is an uppercase letter and has a lowercase equivalent. If no such conversion is possible, the value returned is c unchanged.
7. int **toupper ( int c );**
Convert lowercase letter to uppercase
Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged.
### <cstring>
**此與<string>不同**
1. char * **strcpy ( char * destination, const char * source );**
Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
```
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
strcpy (str2,str1);
strcpy (str3,"copy successful");
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
Output:
str1: Sample string
str2: Sample string
str3: copy successful
```
2. char * **strncpy ( char * destination, const char * source, size_t num );**
Copy characters from string
Copies the first num characters of source to destination.
```
/* strncpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]= "To be or not to be";
char str2[40];
char str3[40];
/* copy to sized buffer (overflow safe): */
strncpy ( str2, str1, sizeof(str2) );
/* partial copy (only 5 chars): */
strncpy ( str3, str2, 5 );
str3[5] = '\0'; /* null character manually added */
puts (str1);
puts (str2);
puts (str3);
return 0;
}
Output:
To be or not to be
To be or not to be
To be
```
3. char * **strcat ( char * destination, const char * source );**
Concatenate strings
Appends a copy of the source string to the destination string.
```
/* strcat example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
puts (str);
return 0;
}
Output:
these strings are concatenated.
```
4. char * strncat ( char * destination, const char * source, size_t num );
Append characters from string
Appends the first num characters of source to destination, plus a terminating null-character.
5. int **strcmp ( const char * str1, const char * str2 );**
Compare two strings
Compares the C string str1 to the C string str2.
```
Returns an integral value indicating the relationship between the strings:
return value indicates
smaller than 0 the first character that does not match has a lower value in ptr1 than in ptr2
0 the contents of both strings are equal
larger than 0 the first character that does not match has a greater value in ptr1 than in ptr2
------------------------------------------
#include <stdio.h>
#include <string.h>
int main ()
{
char key[] = "apple";
char buffer[80];
do {
printf ("Guess my favorite fruit? ");
fflush (stdout);
scanf ("%79s",buffer);
} while (strcmp (key,buffer) != 0);
puts ("Correct answer!");
return 0;
}
Output:
Guess my favourite fruit? orange
Guess my favourite fruit? apple
Correct answer!
```
6. int strncmp ( const char * str1, const char * str2, size_t num );
Compare characters of two strings
Compares up to num characters of the C string str1 to those of the C string str2.
7. const char * **strstr ( const char * str1, const char * str2 )**;
Locate substring
**Returns a pointer to the first occurrence of str2 in str1**, or a null pointer if str2 is not part of str1.
```
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string";
char * pch;
pch = strstr (str,"simple");
strncpy (pch,"sample",6);
puts (str);
return 0;
}
This example searches for the "simple" substring in str
and replaces that word for "sample".
Output:
This is a sample string
```
8. char * **strtok ( char * str, const char * delimiters );**
Split string into tokens
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.
```
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
Output:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
```
9. size_t **strlen ( const char * str );**
Get string length
Returns the length of the C string str.
## Container
### <array>
1. iterator begin()
Return iterator to beginning
Returns an iterator pointing to the first element in the array container.
```
// array::begin example
#include <iostream>
#include <array>
int main ()
{
std::array<int,5> myarray = { 2, 16, 77, 34, 50 };
std::cout << "myarray contains:";
for ( auto it = myarray.begin(); it != myarray.end(); ++it )
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
```
2. iterator end()
3. size_type size()
Return size
Returns the number of elements in the array container.
4. bool empty()
Test whether array is empty
5. reference at ( size_type n );
Access element
Returns a reference to the element at position n in the array.
(The element at the specified position in the array.)
```
// array::at
#include <iostream>
#include <array>
int main ()
{
std::array<int,10> myarray;
// assign some values:
for (int i=0; i<10; i++) myarray.at(i) = i+1;
// print content:
std::cout << "myarray contains:";
for (int i=0; i<10; i++)
std::cout << ' ' << myarray.at(i);
std::cout << '\n';
return 0;
}
```
6. reference front();
Access first element
Returns a reference to the first element in the array container.
7. reference front();
Access last element
Returns a reference to the last element in the array container.
8. void swap (array& x)
Swap content
Exchanges the content of the array by the content of x, which is another array object of the same type (including the same size).
```
// swap arrays
#include <iostream>
#include <array>
int main ()
{
std::array<int,5> first = {10, 20, 30, 40, 50};
std::array<int,5> second = {11, 22, 33, 44, 55};
first.swap (second);
std::cout << "first:";
for (int& x : first) std::cout << ' ' << x;
std::cout << '\n';
std::cout << "second:";
for (int& x : second) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
Output:
first: 11 22 33 44 55
second: 10 20 30 40 50
```
9. void fill (const value_type& val);
Fill array with value
Sets val as the value for “all” the elements in the array object.
### <list>
1. iterator begin()
```
// list::begin
#include <iostream>
#include <list>
int main ()
{
int myints[] = {75,23,65,42,13};
std::list<int> mylist (myints,myints+5);
std::cout << "mylist contains:";
for (std::list<int>::iterator it=mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
```
2. iterator end()
3. empty()
4. size()
5. reference front();
Access first element
Returns a reference to the first element in the list container.
```
// list::front
#include <iostream>
#include <list>
int main ()
{
std::list<int> mylist;
mylist.push_back(77);
mylist.push_back(22);
// now front equals 77, and back 22
mylist.front() -= mylist.back();
std::cout << "mylist.front() is now " << mylist.front() << '\n';
return 0;
}
Output:
mylist.front() is now 55
```
6. reference back();
7. assign
template <class InputIterator>
-> void assign (InputIterator first, InputIterator last);
void assign (size_type n, const value_type& val);
void assign (initializer_list<value_type> il);
```
// list::assign
#include <iostream>
#include <list>
int main ()
{
std::list<int> first;
std::list<int> second;
first.assign (7,100); // 7 ints with value 100
second.assign (first.begin(),first.end()); // a copy of first
int myints[]={1776,7,4};
first.assign (myints,myints+3); // assigning from array
std::cout << "Size of first: " << int (first.size()) << '\n';
std::cout << "Size of second: " << int (second.size()) << '\n';
return 0;
}
Output:
Size of first: 3
Size of second: 7
```
8. void push_front (const value_type& val);
insert element at beginning
9. void pop_front();
Delete first element
10. void push_back (const value_type& val);
Add element at the end
11. void pop_back();
Delete last element
12. insert()
iterator insert (const_iterator position, const value_type& val);
iterator insert (const_iterator position, size_type n, const value_type& val);
template <class InputIterator>
-> iterator insert (const_iterator position, InputIterator first, InputIterator last);
iterator insert (const_iterator position, value_type&& val);
iterator insert (const_iterator position, initializer_list<value_type> il);
Insert elements
The container is extended by inserting new elements before the element at the specified position.
```
// inserting into a list
#include <iostream>
#include <list>
#include <vector>
int main ()
{
std::list<int> mylist;
std::list<int>::iterator it;
// set some initial values:
for (int i=1; i<=5; ++i) mylist.push_back(i); // 1 2 3 4 5
it = mylist.begin();
++it; // it points now to number 2 ^
mylist.insert (it,10); // 1 10 2 3 4 5
// "it" still points to number 2 ^
mylist.insert (it,2,20); // 1 10 20 20 2 3 4 5
--it; // it points now to the second 20 ^
std::vector<int> myvector (2,30);
mylist.insert (it,myvector.begin(),myvector.end());
// 1 10 20 30 30 20 2 3 4 5
// ^
std::cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
mylist contains: 1 10 20 30 30 20 2 3 4 5
```
13. erase()
iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
Erase elements
Removes from the list container either a single element (position) or a range of elements ([first,last)).
```
// erasing from list
#include <iostream>
#include <list>
int main ()
{
std::list<int> mylist;
std::list<int>::iterator it1,it2;
// set some values:
for (int i=1; i<10; ++i) mylist.push_back(i*10);
// 10 20 30 40 50 60 70 80 90
it1 = it2 = mylist.begin(); // ^^
advance (it2,6); // ^ ^
++it1; // ^ ^
it1 = mylist.erase (it1); // 10 30 40 50 60 70 80 90
// ^ ^
it2 = mylist.erase (it2); // 10 30 40 50 60 80 90
// ^ ^
++it1; // ^ ^
--it2; // ^ ^
mylist.erase (it1,it2); // 10 30 60 80 90
// ^
std::cout << "mylist contains:";
for (it1=mylist.begin(); it1!=mylist.end(); ++it1)
std::cout << ' ' << *it1;
std::cout << '\n';
return 0;
}
Output:
mylist contains: 10 30 60 80 90
```
14. void remove (const value_type& val);
Remove elements with specific value
Removes from the container "all" the elements that compare equal to val.
15. merge()
void merge (list& x);
void merge (list& x, Compare comp);
Merge sorted lists
Merges x into the list by transferring all of its elements at their respective ordered positions into the container (both containers shall already be ordered).
```
// list::merge
#include <iostream>
#include <list>
// compare only integral part:
bool mycomparison (double first, double second)
{ return ( int(first)<int(second) ); }
int main ()
{
std::list<double> first, second;
first.push_back (3.1);
first.push_back (2.2);
first.push_back (2.9);
second.push_back (3.7);
second.push_back (7.1);
second.push_back (1.4);
first.sort();
second.sort();
first.merge(second);
// (second is now empty)
second.push_back (2.1);
first.merge(second,mycomparison);
std::cout << "first contains:";
for (std::list<double>::iterator it=first.begin(); it!=first.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
first contains: 1.4 2.2 2.9 2.1 3.1 3.7 7.1
Notice how in the second merger, the function mycomparison (which only compares the integral整數 parts) did not consider 2.1 lower than 2.2 or 2.9, so it was inserted right after them, before 3.1.
```
16. sort()
void sort();
void sort (Compare comp);
17. void reverse()
Reverse the order of elements
### <map>
1. iterator begin();
```
// map::begin/end
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
// show content:
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
Output:
a => 200
b => 100
c => 300
```
2. end(), empty(), size(), erase(), swap(), count(key)
3. mapped_type& at (const key_type& k);
Access element
Returns a reference to the mapped value of the element identified with key k.
```
// map::at
#include <iostream>
#include <string>
#include <map>
int main ()
{
std::map<std::string,int> mymap = {
{ "alpha", 0 },
{ "beta", 0 },
{ "gamma", 0 } };
mymap.at("alpha") = 10;
mymap.at("beta") = 20;
mymap.at("gamma") = 30;
for (auto& x: mymap) {
std::cout << x.first << ": " << x.second << '\n';
}
return 0;
}
Possible output:
alpha: 10
beta: 20
gamma: 30
```
4. insert()
pair<iterator,bool> insert (const value_type& val);
void insert (InputIterator first, InputIterator last);
iterator insert (const_iterator position, const value_type& val);
```
// map::insert (C++98)
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
// first insert function version (single parameter):
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 function version (with hint position):
std::map<char,int>::iterator it = mymap.begin();
mymap.insert (it, std::pair<char,int>('b',300)); // max efficiency inserting
mymap.insert (it, std::pair<char,int>('c',400)); // no max efficiency inserting
// third insert function version (range insertion):
std::map<char,int> anothermap;
anothermap.insert(mymap.begin(),mymap.find('c'));
// showing contents:
std::cout << "mymap contains:\n";
for (it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
std::cout << "anothermap contains:\n";
for (it=anothermap.begin(); it!=anothermap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
Output:
element 'z' already existed with a value of 200
mymap contains:
a => 100
b => 300
c => 400
z => 200
anothermap contains:
a => 100
b => 300
Copies of the elements in the range [first,last) are inserted in the container.
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
```
5. iterator find (const key_type& k);
Get iterator to element
Searches the container for an element with a key equivalent to k and returns an iterator to it if found
```
// map::find
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
it = mymap.find('b');
if (it != mymap.end())
mymap.erase (it);
// print content:
std::cout << "elements in mymap:" << '\n';
std::cout << "a => " << mymap.find('a')->second << '\n';
std::cout << "c => " << mymap.find('c')->second << '\n';
std::cout << "d => " << mymap.find('d')->second << '\n';
return 0;
}
Output:
elements in mymap:
a => 50
c => 150
d => 200
```
### <queue>
1. empty(), size(), front(), back()
2. void push (const value_type& val);
Insert element
Inserts a new element at the end of the queue
```
// queue::push/pop
#include <iostream> // std::cin, std::cout
#include <queue> // std::queue
int main ()
{
std::queue<int> myqueue;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myqueue.push (myint);
} while (myint);
std::cout << "myqueue contains: ";
while (!myqueue.empty())
{
std::cout << ' ' << myqueue.front();
myqueue.pop();
}
std::cout << '\n';
return 0;
}
The example uses push to add a new elements to the queue, which are then popped out in the same order.
```
3. void pop();
Remove next element
Removes the next element in the queue, effectively reducing its size by one.
The element removed is the "oldest" element in the queue whose value can be retrieved by calling member queue::front.
4. void swap();
Swap contents
整個queue都換
```
// queue::swap
#include <iostream> // std::cout
#include <queue> // std::queue
int main ()
{
std::queue<int> foo,bar;
foo.push (10); foo.push(20); foo.push(30);
bar.push (111); bar.push(222);
foo.swap(bar);
std::cout << "size of foo: " << foo.size() << '\n';
std::cout << "size of bar: " << bar.size() << '\n';
return 0;
}
Output:
size of foo: 2
size of bar: 3
```
### <set>
1. iterator begin() / end()
Return iterator to beginning
Returns an iterator referring to the first element in the set container.
Because set containers "keep their elements ordered" at all times, begin points to the element that goes first following the container's sorting criterion.
```
// set::begin/end
#include <iostream>
#include <set>
int main ()
{
int myints[] = {75,23,65,42,13};
std::set<int> myset (myints,myints+5);
std::cout << "myset contains:";
for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
myset contains: 13 23 42 65 75
```
2. insert()
Insert element
Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted.
Because elements in a set are unique, the insertion operation checks whether each inserted element is equivalent to an element already in the container, and if so, the element is not inserted(set數字不重複)
```
// set::insert (C++98)
#include <iostream>
#include <set>
int main ()
{
std::set<int> myset;
std::set<int>::iterator it;
std::pair<std::set<int>::iterator,bool> ret;
// set some initial values:
for (int i=1; i<=5; ++i) myset.insert(i*10); // set: 10 20 30 40 50
ret = myset.insert(20); // no new element inserted
if (ret.second==false) it=ret.first; // "it" now points to element 20
myset.insert (it,25); // max efficiency inserting
myset.insert (it,24); // max efficiency inserting
myset.insert (it,26); // no max efficiency inserting
int myints[]= {5,10,15}; // 10 already in set, not inserted
myset.insert (myints,myints+3);
std::cout << "myset contains:";
for (it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
myset contains: 5 10 15 20 24 25 26 30 40 50
```
3. erase(), find(), count()
### <stack>
1. empty(), size(), swap()
2. reference& top();
Access next element
Returns a reference to the top element in the stack.
3. void push (value_type&& val);
Insert element
Inserts a new element at the top of the stack
4. void pop();
Remove top element
Removes the element on top of the stack
### <vector>
1. begin(), end(), size(), empty(), at(), front(), back(), insert(), erase(), swap()
2. resize()
void resize (size_type n);
void resize (size_type n, const value_type& val);
Change size
Resizes the container so that it contains n elements.
```
// resizing vector
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
// set some initial content:
for (int i=1;i<10;i++) myvector.push_back(i);
myvector.resize(5);
myvector.resize(8,100); // size 8, filled with value(100)
myvector.resize(12); // size 12, default filled with 0
std::cout << "myvector contains:";
for (int i=0;i<myvector.size();i++)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
Output:
myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0
```
3. void reserve (size_type n);
Request a change in capacity
Requests that the vector capacity be at least enough to contain n elements.
```
// vector::reserve
#include <iostream>
#include <vector>
int main ()
{
std::vector<int>::size_type sz;
std::vector<int> foo;
sz = foo.capacity();
std::cout << "making foo grow:\n";
for (int i=0; i<100; ++i) {
foo.push_back(i);
if (sz!=foo.capacity()) {
sz = foo.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
std::vector<int> bar;
sz = bar.capacity();
bar.reserve(100); // this is the only difference with foo above
std::cout << "making bar grow:\n";
for (int i=0; i<100; ++i) {
bar.push_back(i);
if (sz!=bar.capacity()) {
sz = bar.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
return 0;
}
Output:
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 4
capacity changed: 8
capacity changed: 16
capacity changed: 32
capacity changed: 64
capacity changed: 128
making bar grow:
capacity changed: 100
```
4. void push_back (value_type&& val);
Add element at the end
Adds a new element at the end of the vector, after its current last element.
5. void pop_back();
Delete last element
Removes the last element in the vector.
## Input/Output
### <iomanip>
1. setfill (char_type c);
Set fill character
Sets c as the stream's fill character.
```
// setfill example
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setfill, std::setw
int main () {
std::cout << std::setfill ('x') << std::setw (10);
std::cout << 77 << std::endl;
return 0;
}
Output:
xxxxxxxx77
```
2. setw (int n);
Set field width
Sets the field width to be used on output operations.
```
// setw example
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setw
int main () {
std::cout << std::setw(10);
std::cout << 77 << std::endl;
return 0;
}
Output:
77
```
3. setprecision (int n);
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.
```
// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
return 0;
}
Edit & Run
Output:
3.1416
3.14159
3.14159
3.141590000 // fixed讓後面補滿0
```
### <iostream>
1. cin
2. cout
3. fixed
### <sstream>
1. stringstream
專門拿來讀取字串並且處理,很多時候拿來做字串的切割,或者是int跟string類別之間的轉換
把int型態的數字轉成string
此時的stringstream就像個橋樑,可以負責當中間轉換的部分。
stringstream提供了>>與<<運算子來讀取或寫入:
">>" 代表寫入stringstream中,"<<"代表從stringstream拿出。
```
#include <sstream>
using namespace std;
int main()
{
stringstream s1;
int number =1234;
string output;//要把number轉成字串型態的容器
cout << "number=" << number << endl; //顯示number=1234;
s1 << number; //將以int宣告的number放入我們的stringstream中
s1 >> output;
cout<< "output=" << output << endl;//顯示output=1234;
}
st.clear(); // 清除
st.str(""); // 初始化
```
值得注意的是我們兩行顯示都是1234但是他的資料型態卻已經不一樣了,第一個是int的型態,第二行則是string的型態。
## Others
### <algorithm>
1. InputIterator find (InputIterator first, InputIterator last, const T& val);
Find value in range
Returns an iterator to the first element in the range [first,last) that compares equal to val.
If no such element is found, the function returns last.
2. count (InputIterator first, InputIterator last, const T& val);
Count appearances of value in range
Returns the number of elements in the range [first,last) that compare equal to val.
3. equal()
bool equal (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);
bool equal (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred);
Test whether the elements in two ranges are equal
Compares the elements in the range [first1,last1) with those in the range beginning at first2, and returns true if all of the elements in both ranges match.
```
// equal algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::equal
#include <vector> // std::vector
bool mypredicate (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {20,40,60,80,100}; // myints: 20 40 60 80 100
std::vector<int>myvector (myints,myints+5); // myvector: 20 40 60 80 100
// using default comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
myvector[3]=81; // myvector: 20 40 60 81 100
// using predicate comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints, mypredicate) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
return 0;
}
Output:
The contents of both sequences are equal.
The contents of both sequence differ.
```
4. sort()
void sort (RandomAccessIterator first, RandomAccessIterator last);
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Sort elements in range
Sorts the elements in the range [first,last) into ascending order.
```
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
```
5. lower_bound() (upper_bound差不多)
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
Return iterator to lower bound
Returns an iterator pointing to the first element in the range [first,last) which "does not compare less than val".
```
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
// 沒有小於20,停在第一個>=的數字
low=std::lower_bound (v.begin(), v.end(), 20); // ^
// 停在第一個>20的數字
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
```
6. min(), max()
```
// min example
#include <iostream> // std::cout
#include <algorithm> // std::min
int main () {
std::cout << "min(1,2)==" << std::min(1,2) << '\n';
std::cout << "min(2,1)==" << std::min(2,1) << '\n';
std::cout << "min('a','z')==" << std::min('a','z') << '\n';
std::cout << "min(3.14,2.72)==" << std::min(3.14,2.72) << '\n';
return 0;
}
Edit & Run
Output:
min(1,2)==1
min(2,1)==1
min('a','z')==a
min(3.14,2.72)==2.72
```
### <iterator>
### <string>
1. stoi()
Convert string to integer
2. stod()
Convert string to double
3. stof()
Convert string to float
4. to_string()
Convert numerical to string
5. begin()
Iterator to begining
6. end()
Iterator to end