Library functions summary

C / C ++ library function (tolower / toupper) conversion achieved case of letters

Is used in the ctype.h(C ++ is cctype) defined by the following function method library

C:

函数实现原型:
int tolower(int c)//小写
{
    if ((c >= 'A') && (c <= 'Z'))
        return c + ('a' - 'A');
    return c;
}
 
int toupper(int c)//大写
{
    if ((c >= 'a') && (c <= 'z'))
        return c + ('A' - 'a');
    return c;
}

demo-C language

#include<string.h>   //strlen
#include<stdio.h>    //printf
#include<ctype.h>    //tolower
int main()
{
    int i;
    char string[] = "THIS IS A STRING";
    printf("%s\n", string);
    for (i = 0; i < strlen(string); i++)
    {
        string[i] = tolower(string[i]);
    }
    printf("%s\n", string);
    printf("\n");
}

demo-C ++ implementations

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
    string str= "THIS IS A STRING";
    for (int i=0; i <str.size(); i++)
       str[i] = tolower(str[i]);
    cout<<str<<endl;
    return 0;
}

next_permutation()


For next_permutation function, which is a function prototype:

​ #include

​ bool next_permutation(iterator start,iterator end)

When a sequence is not present in the current arrangement, the function returns false, true otherwise

The prev_permutation function will turn, and returns false when a sort does not exist, true otherwise

#include <iostream> 
#include <algorithm> 
using namespace std; 
int main() 
{ 
    int num[5]={1,2,3}; //此时应该是升序,中间出现逆序的会无法出现全部排序
    do 
    { 
        cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl; 
    }while(next_permutation(num,num+3)); 
    return 0; 
} 

After the run can be found, next_permutation (num, num + n ) is a function of the array num first n elements full array, and simultaneously changing the value of the num array.

In addition, it is emphasized that, next_permutation () needs to be arranged in ascending order of the array before use, or can only find out after several full array of the sequence.

prev_premutation () and the next ... contrary

qsort()

Function declarations

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

parameter

  • Base - a pointer to the first element of the array to be sorted.
  • nitems number pointed to by the base element of the array -.
  • size - size of each element of the array, in bytes.
  • The compar - function for comparing two elements.

return value

This function does not return a value.

#include <stdio.h>
#include <stdlib.h>

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int main()
{
   int n;

   printf("排序之前的列表:\n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 5, sizeof(int), cmpfunc);

   printf("\n排序之后的列表:\n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }
  
  return(0);
}

C ++ rand with srand usage

The computer is a random number by a pseudo-random number that is generated by a small sequence of polynomial M, wherein each generated sequence has a small initial value, i.e. the random seed. (Note: Small M period sequence polynomial is 65535, that is, each using a random seed generated random number is 65535 cycles, when you get 65,535 random numbers are repeated there.)

We know that rand () function can be used to generate random numbers, but this is not true in the sense of random numbers, it is a pseudo-random number is based on a number (we can call it the seeds) as a benchmark to calculate a recursive formula a series of numbers out, when a large number of series this time, it is in line with normal announcement, which is equivalent to generate a random number, but this is not true random numbers, when the computer boots up, the value of this seed is set up unless you destroy the system.

rand()

Function: Random number generator

usage:

int rand(void)
  
所在头文件:  stdlib.h

Internal rand () implementation is done using a linear congruential method, it is not really random, because of their particularly long period, so that in a certain range can be regarded as random.

rand () returns a random number value in a range between 0 to RAND_MAX. RAND_MAX range is between a minimum of 32767 (int). 65535 is a two-byte unsigned int, four-byte integer ranging 4294967295. 0 ~ RAND_MAX probability of each selected number are the same.

When the user does not set the random number seed, the default is a random number seed.

rand () is a pseudo-random number generated, each execution is the same; to different () function initializes it with the srand.

srand()

Function: initialize the random number generator

usage:

void srand(unsigned int seed)
  
所在头文件:  stdlib.h

srand () to set the rand () generates a random number at the random number seed. Seed parameter must be an integer, if each set are the same seed value, a random value rand () will be generated every time the same.

As the clock using the current random number seed

rand () random number generated in each run are identical with the last. To different, () to initialize it with the function srand. May be utilized srand ((unsigned int) (time (NULL)) method, produce different random number seed, because every program run time is different.

Usage of generating random numbers

  • 1) to srand () providing a seed, which is a type unsigned int;
  • 2) Call rand (), it returns the value of a random number (between 0 and RAND_MAX) The seed as srand () a;
  • 3) According to several calls rand (), so as to continuously obtain a new random number;
  • 4) At any time, you can give srand () provides a new seed to further "randomized" rand () output.

A random number between 0 ~ RAND_MAX procedure

#include <iostream>
#include <stdlib.h>
#include <time.h> 

using namespace std; 

int main()
{ 
        srand((unsigned)time(NULL)); 
        for(int i = 0; i < 10;i++ ) 
                cout << rand() << '/t';
        cout << endl; 
        return 0;
}

A certain range of random numbers represented by general formula

要取得 [a,b) 的随机整数,使用 (rand() % (b-a))+ a;

要取得 [a,b] 的随机整数,使用 (rand() % (b-a+1))+ a;

要取得 (a,b] 的随机整数,使用 (rand() % (b-a))+ a + 1;

通用公式: a + rand() % n;其中的 a 是起始值,n 是整数的范围。

要取得 a 到 b 之间的随机整数,另一种表示:a + (int)b * rand() / (RAND_MAX + 1)。

要取得 0~1 之间的浮点数,可以使用 rand() / double(RAND_MAX)。

stringstream

stringstream Another type of string C ++ provides a stream (stream) objects, and the previous learned  iostream、fstream similar operation. To use  stringstream, you must first add this line:

#include

stringstream Mainly used in a string split, you can specify the contents of the string is set to start with a clear () and str (), then >> the individual data output, for example:

string s;
stringstream ss;
int a, b, c;
getline(cin, s);
ss.clear();
ss.str(s);
ss >> a >> b >> c;

Here we see a use  stringstream example:

Title: The first line of input there is a number N represents the next N lines there are data, each row of data, there is not a fixed integer number (up to 20 per line maximum 200 characters), you will write a program the sum of each row printed out.

Input:

3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999

Output:

6
251
4995

Program are as follows:

string s;
stringstream ss;
int n, i, sum, a;
cin >> n;
getline(cin, s); // 讀取換行
for (i=0; i<n; i++)
{
getline(cin, s);
ss.clear();
ss.str(s);
sum=0;
while (1)
{
    ss >> a;
    if ( ss.fail() ) break;
    sum+=a;
}
cout << sum << endl;
}
                    [stringstream使用详解](https://blog.csdn.net/xw20084898/article/details/21939811)

find function string class

count function

头文件 algorithm

Function is similar to find. This function uses a pair of iterators and a value as an argument and returns the value of the number of statistical results appear.

Write a program to read a series int data type, and stores them into vector objects, and then specify the value of a statistical appeared many times.

cout<<count(ivec.begin() , ivec.end() , searchValue)

Implementation:

//读取一系列int数据,并将它们存储到vector对象中,  
//然后使用algorithm头文件中定义的名为count的函数,  
//统计某个指定的值出现了多少次  
#include<iostream>  
#include<vector>  
#include<algorithm>  
using namespace std;  

int main()  
{  
    int ival , searchValue;  
    vector<int> ivec;  

    //读入int型数据并存储到vector对象中,直至遇到文件结束符  
    cout<<"Enter some integers(Ctrl+Z to end): "<<endl;  
    while(cin >> ival)  
        ivec.push_back(ival);  

    cin.clear(); // 使输入流重新有效  

    //读入欲统计其出现次数的int值  
    cout<<"Enter an integer you want to search: "<<endl;  
    cin>>searchValue;  

    //使用count函数统计该值出现的次数并输出结果  
    cout<<count(ivec.begin() , ivec.end() , searchValue)  
        <<"  elements in the vector have value "  
        <<searchValue<<endl;  

    return 0;  
}  

count_if function

count_if: Returns the number of elements specified interval satisfies the condition.

template

#include <vector>  
#include <algorithm>  
#include <iostream>  

bool greater10(int value)  
{  
    return value >10;  
}  

int main()  
{  
    using namespace std;  
    vector<int> v1;  
    vector<int>::iterator Iter;  

    v1.push_back(10);  
    v1.push_back(20);  
    v1.push_back(10);  
    v1.push_back(40);  
    v1.push_back(10);  

    cout << "v1 : ";  
    for (Iter = v1.begin(); Iter != v1.end(); Iter++)  
       cout << *Iter << " ";  
    cout << endl;  


    vector<int>::size_type  result1 = count_if(v1.begin(), v1.end(), greater10);  //count_if算法返回使谓词函数返回条件成立的元素个数  
    cout << "The number of elements in v1 greater than 10 is: "  
         << result1 << "." << endl;  

    return 0;  
}  

Predicates (predicate): do certain functions of detection, to determine the conditions for the return type, pointed out that condition is satisfied.
Summary:
COUNT: count the number of times a value occurs in a sequence

count_if: count the number of times a predicate match in the sequence

Greater () and less () function

greater and less header files Two structures defined, are achieved by overriding the comparator function () operator.

greater is defined as follows:

template <class T> struct greater {
  bool operator() (const T& x, const T& y) const {return x>y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};

less is defined as follows:

template <class T> struct less {
  bool operator() (const T& x, const T& y) const {return x<y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};

Specific use

#include<iostream>
#include<algorithm>//因为用了sort()函数
#include<functional>//因为用了greater<int>()
using namespace std;
 
void main()
{
    int a[]={3,1,4,2,5};
    int i;
    int len=sizeof(a)/sizeof(int);//这里切记要除以sizeof(int)!

    sort(a ,a + len, greater<int>());//内置类型的由大到小排序
    for(i=0;i<len;i++)
        cout<<a[i]<<" ";
    cout<<"\n";
    sort(a, a + len, less<int>());//内置类型的由小到大排序
    for(i=0;i<len;i++)
        cout<<a[i]<<" ";
}

priority_queue usage

头文件 : #include<queue>
定义: priority_queue<int> p;

Big priority output data

priority_queue<Type, Container, Functional>

Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。

如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。

举例:
#include<iostream>
#include<queue>
using namespace std;
 
int main(){
    priority_queue<int> p;
    p.push(1);
    p.push(2);
    p.push(8);
    p.push(5);
    p.push(43);
    for(int i=0;i<5;i++){
        cout<<p.top()<<endl;
        p.pop();
    }
    return 0;
}

Small priority output data

method one
priority_queue<int, vector<int>, greater<int> > p;

For example

#include<iostream>
#include<queue>
using namespace std;
 
int main(){
    priority_queue<int, vector<int>, greater<int> >p;
    p.push(1);
    p.push(2);
    p.push(8);
    p.push(5);
    p.push(43);
    for(int i=0;i<5;i++){
        cout<<p.top()<<endl;
        p.pop();
    }
    return 0;
}

Method two: custom priority override the default of <symbols

For example:

#include<iostream>
#include<queue>
#include<cstdlib>
using namespace std;
struct Node{
    int x,y;
    Node(int a=0, int b=0):
        x(a), y(b) {}
};
 
struct cmp{
    bool operator()(Node a, Node b){
        if(a.x == b.x)  return a.y>b.y;
        return a.x>b.x;
    }
};
 
int main(){
    priority_queue<Node, vector<Node>, cmp>p;
    
    for(int i=0; i<10; ++i)
        p.push(Node(rand(), rand()));
        
    while(!p.empty()){
        cout<<p.top().x<<' '<<p.top().y<<endl;
        p.pop();
    }//while
    //getchar();
    return 0;
}


STL suited to the scene

vector and list set mulitset map mulitmap
Memory Architecture Single-ended array An array of double-ended Doubly linked list Binary Tree Binary Tree Binary Tree Binary Tree
Random storage Yes Yes no no no For the key, not no
Elements of the search speed slow slow very slow fast fast For the key, fast For the key, fast
Element insert delete position The end of Head and tail ends any position --- --- --- ---

list form
vector sequence in elemental
deque queue
map key - value, Dictionary
set in text processing, can be used to save the word you want to ignore.


Whether isdigit () checks preaching character is a decimal digit character

description

C library functions void isdigit (int c) Check the preaching character is a decimal digit character.

Is a decimal number: 0123456789

Function declarations

int isdigit(int c);

返回值: 如果 c 是一个数字,则该函数返回非零值,否则返回 0。
实例
#include <stdio.h>
#include <ctype.h>

int main()
{
   int var1 = 'h';
   int var2 = '2';
    
   if( isdigit(var1) )
   {
      printf("var1 = |%c| 是一个数字\n", var1 );
   }
   else
   {
      printf("var1 = |%c| 不是一个数字\n", var1 );
   }
   if( isdigit(var2) )
   {
      printf("var2 = |%c| 是一个数字\n", var2 );
   }
   else
   {
      printf("var2 = |%c| 不是一个数字\n", var2 );
   }
  
   return(0);
}

result

var1 = |h| 不是一个数字
var2 = |2| 是一个数字

stoi analytic function

Features

The n-ary conversion to decimal string

usage

stoi(字符串,起始位置,n进制),将 n 进制的字符串转化为十进制
 
示例:
stoi(str, 0, 2); //将字符串 str 从 0 位置开始到末尾的 2 进制转换为十进制

head File

#include <string>

Examples

#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    string str = "1010";
    
    int a = stoi(str, 0, 2);
 
    cout << a << endl;
}

//输出10

iota function

Function prototype

template <class ForwardIterator, class T>
  void iota (ForwardIterator first, ForwardIterator last, T val);

等价于
template<class _FwdIt,class _Ty> inline
    void _Iota(_FwdIt _First, _FwdIt _Last, _Ty _Val)
{   // compute increasing sequence into [_First, _Last)
    for (; _First != _Last; ++_First, ++_Val)
        *_First = _Val;
}
parameter:
  • first,last:

    Sequence and pointing to the initial position at the end of the forward iterator (Forward Iterators). This range, i.e., [first, last), comprising first to last among all elements, including first element pointed to, but not including the last element directed.

  • val: an initial value of accumulation.

Features

Assignment element within the specified range with the order of increasing value.

Examples

// iota example
#include <iostream>     // std::cout
#include <numeric>      // std::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

Guess you like

Origin www.cnblogs.com/Kanna/p/12329707.html
Recommended