STL中算法锦集(一)

STL中算法锦集(一)

文章目录

  • STL中算法锦集(一)
    • 一、< algorithm >
      • 1.std::adjacent_find
      • 2.std::all_of
      • 3.std::any_of
      • 4.std::binary_search
      • 5.std::copy
      • 6.std::copy_backward
      • 7.std::copy_if
      • 8.std::copy_n
      • 9.std::count
      • 10.std::count_if

一、< algorithm >

虽然这一部分不一定要全部掌握,但是掌握可以更快捷、方便的编程

1.std::adjacent_find

  • 原型:
template <class ForwardIterator>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last);

template <class ForwardIterator, class BinaryPredicate>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
  • 参数:
  • ForwardIterator first:区间的开始
  • ForwardIterator last:区间的结束
  • BinaryPredicate pred:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:在[first,last)这个范围中搜索两个连续、满足pred条件、且是第一次出现的元素位置
  • 返回值:如果找到这两个元素对,返回first迭代器,如果没有找到这两个元素对,则返回last迭代器
  • 实现:
template <class ForwardIterator>
ForwardIterator adjacent_find (ForwardIterator first,ForwardIterator last)
{
  if (first != last)
  {
    ForwardIterator next = first; 
    ++next;
    while (next != last) 
    {
      // or: if (pred(*first,*next))
      if (*first == *next)
        return first;
        
      ++first; 
      ++next;
    }
  }
  return last;
}
  • 案例:
// adjacent_find example
#include      // std::cout
#include     // std::adjacent_find
#include        // std::vector

bool myfunction (int i, int j) 
{
  return (i==j);
}

int main () 
{
  int myints[] = {5,20,5,30,30,20,10,10,20};
  std::vector<int> myvector (myints,myints+8);
  std::vector<int>::iterator it;

  // using default comparison:
  it = std::adjacent_find (myvector.begin(), myvector.end());

  if (it!=myvector.end())
    std::cout << "the first pair of repeated elements are: " << *it << '\n';

  //using predicate comparison:
  it = std::adjacent_find (++it, myvector.end(), myfunction);

  if (it != myvector.end())
    std::cout << "the second pair of repeated elements are: " << *it << '\n';

  return 0;
}

Output:
the first pair of repeated elements are: 30
the second pair of repeated elements are: 10

2.std::all_of

  • 原型:
template <class InputIterator, class UnaryPredicate>
  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
  • 参数:
  • InputIterator first:区间的开始
  • InputIterator last:区间的结束
  • UnaryPredicate pred:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:判断[first,last)区间中的所有元素是否满足pred条件
  • 返回值:如果全部满足pred条件返回true,反之有一个不满足条件返回false
  • 实现:
template<class InputIterator, class UnaryPredicate>
  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first != last) 
  {
    if (!pred(*first)) 
    	return false;
    ++first;
  }
  return true;
}
  • 案例:
// all_of example
#include      // std::cout
#include     // std::all_of
#include         // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i % 2;}) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}
 
Output:
All the elements are odd numbers.

3.std::any_of

  • 原型:
template <class InputIterator, class UnaryPredicate>
  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
  • 参数:
  • InputIterator first:区间的开始
  • InputIterator last:区间的结束
  • UnaryPredicate pred:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:判断[first,last)区间中是否有元素是否满足pred条件
  • 返回值:如果有任意一个元素满足pred条件就返回true,反之返回false
  • 实现:
template<class InputIterator, class UnaryPredicate>
  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return true;
    ++first;
  }
  return false;
}
  • 案例:
// any_of example
#include      // std::cout
#include     // std::any_of
#include         // std::array

int main () {
  std::array<int,7> foo = {0,1,-1,3,-3,5,-5};

  if ( std::any_of(foo.begin(), foo.end(), [](int i){return i < 0;}) )
    std::cout << "There are negative elements in the range.\n";

  return 0;
}

Output:
There are negative elements in the range.

4.std::binary_search

  • 原型:
template <class ForwardIterator, class T>
  bool binary_search (ForwardIterator first, ForwardIterator last,
                      const T& val);

template <class ForwardIterator, class T, class Compare>
  bool binary_search (ForwardIterator first, ForwardIterator last,
                      const T& val, Compare comp);
  • 参数:
  • ForwardIterator first:区间的开始
  • ForwardIterator last:区间的结束
  • const T& val:待搜索的val
  • Compare comp:自定义的比较器,因为元素可能是自定义的
  • 作用:二分查找区间中是否包含val元素
  • 返回值:如果包含返回true,反之返回false
  • 实现:
template <class ForwardIterator, class T>
  bool binary_search (ForwardIterator first, ForwardIterator last, const T& val)
{
  first = std::lower_bound(first,last,val);
  return (first != last && !(val < *first));
}
  • 案例:
// binary_search example
#include      // std::cout
#include     // std::binary_search, std::sort
#include        // std::vector

bool myfunction (int i,int j) { return (i < j); }

int main () {
  int myints[] = {1,2,3,4,5,4,3,2,1};
  std::vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1

  // using default comparison:
  std::sort (v.begin(), v.end());

  std::cout << "looking for a 3... ";
  if (std::binary_search (v.begin(), v.end(), 3))
    std::cout << "found!\n"; 
  else 
    std::cout << "not found.\n";

  // using myfunction as comp:
  std::sort (v.begin(), v.end(), myfunction);

  std::cout << "looking for a 6... ";
  if (std::binary_search (v.begin(), v.end(), 6, myfunction))
    std::cout << "found!\n"; else std::cout << "not found.\n";

  return 0;
}

Output:
looking for a 3... found!
looking for a 6... not found.

5.std::copy

  • 原型:
template <class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
  • 参数:
  • InputIterator first:区间的开始
  • InputIterator last:区间的结束
  • OutputIterator result:拷贝区间的开始位置
  • 注意[first,last)区间和result不能够重叠,否则会报错
  • 作用:把[first,last)区间当中的所有元素拷贝到result空间中
  • 返回值:返回拷贝后的空间末尾位置的迭代器
  • 实现:
template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first != last) {
    *result = *first;
    ++result;
    ++first;
  }
  return result;
}
  • 案例:
// copy algorithm example
#include      // std::cout
#include     // std::copy
#include        // std::vector

int main () {
  int myints[]={10,20,30,40,50,60,70};
  std::vector<int> myvector (7);

  std::copy ( myints, myints+7, myvector.begin() );

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

  std::cout << '\n';

  return 0;
}

Output:
myvector contains: 10 20 30 40 50 60 70

6.std::copy_backward

  • 原型:
template <class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 copy_backward (BidirectionalIterator1 first,
                                        BidirectionalIterator1 last,
                                        BidirectionalIterator2 result);
  • 参数:
  • BidirectionalIterator1 first:区间的开始
  • BidirectionalIterator1 last:区间的结束
  • BidirectionalIterator2 result:拷贝区间的末尾位置
  • 注意[first,last)区间和result能够不会重叠,会报错
  • copy是正向copy的,而copy_backward是反向copy的,copy_backward区间如果冲突就会把前面区间的元素覆盖掉
  • 作用:把[first,last)区间当中的所有元素拷贝到result空间中
  • 返回值:返回拷贝后的空间第一个位置的迭代器
  • 实现:
template<class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 copy_backward ( BidirectionalIterator1 first,
                                         BidirectionalIterator1 last,
                                         BidirectionalIterator2 result )
{
  while (last != first) 
  	*(--result) = *(--last);
  return result;
}
  • 案例:
// copy_backward example
#include      // std::cout
#include     // std::copy_backward
#include        // 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;
}


Output:
myvector contains: 10 20 30 10 20 30 40 50

7.std::copy_if

  • 原型:
template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred);
  • 参数:
  • InputIterator first:区间的开始
  • InputIterator last:区间的结束
  • OutputIterator result:拷贝区间的开始位置
  • UnaryPredicate pred:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:[first,last)区间中的元素如果满足pred条件就copy到result中
  • 返回值:返回拷贝后的空间末尾位置的迭代器
  • 实现:
template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) {
      *result = *first;
      ++result;
    }
    ++first;
  }
  return result;
}
  • 案例:
// copy_if example
#include      // std::cout
#include     // std::copy_if, std::distance
#include        // std::vector

int main () {
  std::vector<int> foo = {25,15,5,-5,-15};
  std::vector<int> bar (foo.size());

  // copy only positive numbers:
  auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i < 0);} );
  bar.resize(std::distance(bar.begin(),it));  // shrink container to new size

  std::cout << "bar contains:";
  for (int& x: bar) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

Output:
bar contains: 25 15 5

8.std::copy_n

  • 原型:
template <class InputIterator, class Size, class OutputIterator>
  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);
  • 参数:
  • InputIterator first:区间的开始
  • Size n:拷贝元素的个数
  • OutputIterator result:拷贝区间的开始位置
  • 作用:从first拷贝n个元素到result当中
  • 返回值:返回拷贝区间的末尾位置的迭代器
  • 实现:
template<class InputIterator, class Size, class OutputIterator>
  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result)
{
  while (n > 0) {
    *result = *first;
    ++result; ++first;
    --n;
  }
  return result;
}
  • 案例:
// copy_n algorithm example
#include      // std::cout
#include     // std::copy
#include        // std::vector

int main () {
  int myints[]={10,20,30,40,50,60,70};
  std::vector<int> myvector;

  myvector.resize(7);   // allocate space for 7 elements

  std::copy_n ( myints, 7, myvector.begin() );

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

  std::cout << '\n';

  return 0;
}

Output:
myvector contains: 10 20 30 40 50 60 70

9.std::count

  • 原型:
template <class InputIterator, class T>
  typename iterator_traits<InputIterator>::difference_type
    count (InputIterator first, InputIterator last, const T& val);
  • 参数:
  • InputIterator first:区间的开始
  • InputIterator last:区间的结束
  • const T& val:待计数的val
  • 作用:[first,last)区间中值为val的元素的个数
  • 返回值:返回值为val的元素的个数
  • 实现:
template <class InputIterator, class T>
  typename iterator_traits<InputIterator>::difference_type
    count (InputIterator first, InputIterator last, const T& val)
{
  typename iterator_traits<InputIterator>::difference_type ret = 0;
  while (first!=last) {
    if (*first == val) 
    	++ret;
    ++first;
  }
  return ret;
}
  • 案例:
// count algorithm example
#include      // std::cout
#include     // std::count
#include        // std::vector

int main () {
  // counting elements in array:
  int myints[] = {10,20,30,30,20,10,10,20};   // 8 elements
  int mycount = std::count (myints, myints+8, 10);
  std::cout << "10 appears " << mycount << " times.\n";

  // counting elements in container:
  std::vector<int> myvector (myints, myints+8);
  mycount = std::count (myvector.begin(), myvector.end(), 20);
  std::cout << "20 appears " << mycount  << " times.\n";

  return 0;
}

Output:
10 appears 3 times.
20 appears 3 times.

10.std::count_if

  • 原型:
template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
  • 参数:
  • InputIterator first:区间的开始
  • InputIterator last:区间的结束
  • UnaryPredicate pred:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:求[first,last)区间内满足pred条件的元素的个数
  • 返回值:满足pred条件的元素的个数
  • 实现:
template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  typename iterator_traits<InputIterator>::difference_type ret = 0;
  while (first!=last) {
    if (pred(*first)) ++ret;
    ++first;
  }
  return ret;
}
  • 案例:
// count_if example
#include      // std::cout
#include     // std::count_if
#include        // std::vector

bool IsOdd (int i) { return ((i % 2) == 1); }

int main () {
  std::vector<int> myvector;
  for (int i=1; i<10; i++) 
  	myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9

  int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
  std::cout << "myvector contains " << mycount  << " odd values.\n";

  return 0;
}

Output:
myvector contains 5 odd values.

你可能感兴趣的:(C/C++)