c++常用函數摘抄

來源:互聯網
上載者:User

標籤:

1.標準初始化函數

   std::fill(首地址,尾地址,value)      || 用於在首尾地址之間填充value值,對應matlab的ones(1:n)函數

1 template <class ForwardIterator, class T>2   void fill (ForwardIterator first, ForwardIterator last, const T& val)3 {4   while (first != last) {5     *first = val;6     ++first;7   }8 }
 1 // fill algorithm example 2 #include <iostream>     // std::cout 3 #include <algorithm>    // std::fill 4 #include <vector>       // std::vector 5  6 int main () { 7   std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0 8  9   std::fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 010   std::fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 011 12   std::cout << "myvector contains:";13   for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)14     std::cout << ‘ ‘ << *it;15   std::cout << ‘\n‘;16 17   return 0;18 }
myvector contains: 5 5 5 8 8 8 0 0

 

2.交換函數

  std::swap(value1,value2)


1 template <class T> void swap ( T& a, T& b )2 {3   T c(a); a=b; b=c;4 }
 1 // swap algorithm example (C++11) 2 #include <iostream>     // std::cout 3 #include <utility>      // std::swap 4  5 int main () { 6  7   int x=10, y=20;                  // x:10 y:20 8   std::swap(x,y);                  // x:20 y:10 9 10   int foo[4];                      // foo: ?  ?  ?  ?11   int bar[] = {10,20,30,40};       // foo: ?  ?  ?  ?    bar: 10 20 30 4012   std::swap(foo,bar);              // foo: 10 20 30 40   bar: ?  ?  ?  ?13 14   std::cout << "foo contains:";15   for (int i: foo) std::cout << ‘ ‘ << i;16   std::cout << ‘\n‘;17 18   return 0;19 }
foo contains: 10 20 30 40

 

 

 


c++常用函數摘抄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.