文件库函数解析(1)

时间:2022-06-17
本文章向大家介绍文件库函数解析(1),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

algorithm为算法库,里面部分的函数需要编译的环境为c++11 对于我使用Devc++设置环境的方法如下

只需要改成 g++ -std=c++11就可以了,好下面就来解析


all_of函数

bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);

第一个参数,第二个参数为迭代器或者数组地址,第三个为一元谓语函数 (就是一个参数的函数) 作用:判断该函数里的元素是否都满足pred,如果都满足,则返回真

#include<iostream>
#include<algorithm>

using namespace std;

int operation(int a)
{
    return a%2;
}
int main()
{
    int num[5] = {1,3,5,7,9};
    if(all_of(num,num+5,operation))
    {
        cout << "yes";
    }
    return 0;
}

any_of函数

 bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

作用:判断一组数据中是否存在一个元素满足这个条件,如果满足,则返回真

binary_search函数

bool binary_search (ForwardIterator first, ForwardIterator last,
                      const T& val);
bool binary_search (ForwardIterator first, ForwardIterator last,
                      const T& val, Compare comp);
  1. 在数据中是否存在等于val的数
  2. 在数据中是否有满足comp函数的数(comp是二元谓语函数,val在第二个位置)

copy函数

 OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

作用:将数据复制到起始点为result的迭代器处,数据范围[first,last);

copy_backward函数

BidirectionalIterator2 copy_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);

作用:从result的位置开始依次往前复制(last,first]的值

#include <iostream>     // std::cout
#include <algorithm>    // std::copy_backward
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector;

  // set some values:
  for (int i=1; i<=5; i++)
    myvector.push_back(i*10);          // myvector: 10 20 30 40 50

  myvector.resize(myvector.size()+3);  // allocate space for 3 more elements

  std::copy_backward ( myvector.begin(), myvector.begin()+5, myvector.end() );

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << 'n';

  return 0;
}

copy_if

OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);

作用:满足pred函数就开始复制到result上,返回迭代器地址。

copy_n函数 OutputIterator copy_n (InputIterator first, Size n, OutputIterator result); 从first出复制n个数据到result中