C++ STL学习资源

C++ STL总结

一、STL简介(转载自:https://www.cnblogs.com/CnZyy/p/3317999.html)

STL(Standard Template Library,标准模板库)是惠普实验室开发的一系列软件的统称。它是由Alexander Stepanov、Meng Lee和David R Musser在惠普实验室工作时所开发出来的。现在虽说它主要出现在C++中,但在被引入C++之前该技术就已经存在了很长的一段时间。STL的代码从广义上讲分为三类:algorithm(算法)、container(容器)和iterator(迭代器),几乎所有的代码都采用了模板类和模版函数的方式,这相比于传统的由函数和类组成的库来说提供了更好的代码重用机会。在C++标准中,STL被组织为下面的13个头文件:<algorithm>、<deque>、<functional>、<iterator>、<vector>、<list>、<map>、<memory>、<numeric>、<queue>、<set>、<stack>和<utility>。

二、算法

大家都能取得的一个共识是函数库对数据类型的选择对其可重用性起着至关重要的作用。举例来说,一个求方根的函数,在使用浮点数作为其参数类型的情况下的可重用性肯定比使用整型作为它的参数类性要高。而C++通过模板的机制允许推迟对某些类型的选择,直到真正想使用模板或者说对模板进行特化的时候,STL就利用了这一点提供了相当多的有用算法。它是在一个有效的框架中完成这些算法的——你可以将所有的类型划分为少数的几类,然后就可以在模版的参数中使用一种类型替换掉同一种类中的其他类型。STL提供了大约100个实现算法的模版函数,比如算法for_each将为指定序列中的每一个元素调用指定的函数,stable_sort以你所指定的规则对序列进行稳定性排序等等。这样一来,只要我们熟悉了STL之后,许多代码可以被大大的化简,只需要通过调用一两个算法模板,就可以完成所需要的功能并大大地提升效率。算法部分主要由头文件<algorithm>,<numeric>和<functional>组成。

<algorithm>是所有STL头文件中最大的一个(尽管它很好理解),它是由一大堆模版函数组成的,可以认为每个函数在很大程度上都是独立的,其中常用到的功能范围涉及到比较、交换、查找、遍历操作、复制、修改、移除、反转、排序、合并等等。<numeric>体积很小,只包括几个在序列上面进行简单数学运算的模板函数,包括加法和乘法在序列上的一些操作。<functional>中则定义了一些模板类,用以声明函数对象。

三、容器

在实际的开发过程中,数据结构本身的重要性不会逊于操作于数据结构的算法的重要性,当程序中存在着对时间要求很高的部分时,数据结构的选择就显得更加重要。经典的数据结构数量有限,但是我们常常重复着一些为了实现向量、链表等结构而编写的代码,这些代码都十分相似,只是为了适应不同数据的变化而在细节上有所出入。STL容器就为我们提供了这样的方便,它允许我们重复利用已有的实现构造自己的特定类型下的数据结构,通过设置一些模版类,STL容器对最常用的数据结构提供了支持,这些模板的参数允许我们指定容器中元素的数据类型,可以将我们许多重复而乏味的工作简化。容器部分主要由头文件<vector>,<list>,<deque>,<set>,<map>,<stack>和<queue>组成。对于常用的一些容器和容器适配器(可以看作由其它容器实现的容器),可以通过下表总结一下它们和相应头文件的对应关系。向量(vector) 连续存储的元素<vector>,列表(list)由节点组成的双向链表,每个结点包含着一个元素<list>,双队列(deque) 连续存储的指向不同元素的指针所组成的数组<deque>,集合(set) 由节点组成的红黑树,每个节点都包含着一个元素,节点之间以某种作用于元素对的谓词排列,没有两个不同的元素能够拥有相同的次序 <set>多重集合(multiset) 允许存在两个次序相等的元素的集合 <set>,栈(stack) 后进先出的值的排列 <stack>,队列(queue) 先进先出的执的排列 <queue>,优先队列(priority_queue) 元素的次序是由作用于所存储的值对上的某种谓词决定的的一种队列 <queue>,映射(map) 由{键,值}对组成的集合,以某种作用于键对上的谓词排列 <map>,多重映射(multimap) 允许键对有相等的次序的映射 <map>。

四、迭代器

下面要说的迭代器从作用上来说是最基本的部分,可是理解起来比前两者都要费力一些(至少笔者是这样)。软件设计有一个基本原则,所有的问题都可以通过引进一个间接层来简化,这种简化在STL中就是用迭代器来完成的。概括来说,迭代器在STL中用来将算法和容器联系起来,起着一种黏和剂的作用。几乎STL提供的所有算法都是通过迭代器存取元素序列进行工作的,每一个容器都定义了其本身所专有的迭代器,用以存取容器中的元素。迭代器部分主要由头文件<utility>,<iterator>和<memory>组成。<utility>是一个很小的头文件,它包括了贯穿使用在STL中的几个模板的声明,<iterator>中提供了迭代器使用的许多方法,而对于<memory>的描述则十分的困难,它以不同寻常的方式为容器中的元素分配存储空间,同时也为某些算法执行期间产生的临时对象提供机制,<memory>中的主要部分是模板类allocator,它负责产生所有容器中的默认分配器。

对于之前不太了解STL的读者来说,上面的文字只是十分概括地描述了一下STL的框架,对您理解STL的机制乃至使用STL所起到的帮助微乎甚微,这不光是因为深入STL需要对C++的高级应用有比较全面的了解,更因为STL的三个部分算法、容器和迭代器三部分是互相牵制或者说是紧密结合的。从概念上讲最基础的部分是迭代器,可是直接学习迭代器会遇到许多抽象枯燥和繁琐的细节,然而不真正理解迭代器又是无法直接进入另两部分的学习的(至少对剖析源码来说是这样)。可以说,适应STL处理问题的方法是需要花费一定的时间的,但是以此为代价,STL取得了一种十分可贵的独立性,它通过迭代器能在尽可能少地知道某种数据结构的情况下完成对这一结构的运算,所以下决心钻研STL的朋友们千万不要被一时的困难击倒。其实STL运用的模式相对统一,只要适应了它,从一个STL工具到另一个工具,都不会有什么大的变化。

对于STL的使用,也普遍存在着两种观点。第一种认为STL的最大作用在于充当经典的数据结构和算法教材,因为它的源代码涉及了许多具体实现方面的问题。第二种则认为STL的初衷乃是为了简化设计,避免重复劳动,提高编程效率,因此应该是“应用至上”的,对于源代码则不必深究。笔者则认为分析源代码和应用并不矛盾,通过分析源代码也能提高我们对其应用的理解,当然根据具体的目的也可以有不同的侧重。

下面进行细致总结和分析(http://www.cplusplus.com/reference/stl/)

// 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;

}

 

// array::back#include <iostream>#include <array>

int main ()

{

  std::array<int,3> myarray = {5, 19, 77};

 

  std::cout << "front is: " << myarray.front() << std::endl;   // 5

  std::cout << "back is: " << myarray.back() << std::endl;     // 77

 

  myarray.back() = 50;

 

  std::cout << "myarray now contains:";

  for ( int& x : myarray ) std::cout << ' ' << x;

  std::cout << '\n';

 

  return 0;

}

// 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;

}

// array::cbegin 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.cbegin(); it != myarray.cend(); ++it )

    std::cout << ' ' << *it;   // cannot modify *it

 

  std::cout << '\n';

 

  return 0;

}

// array::crbegin/crend#include <iostream>#include <array>

int main ()

{

  std::array<int,6> myarray = {10, 20, 30, 40, 50, 60} ;

 

  std::cout << "myarray backwards:";

  for ( auto rit=myarray.crbegin() ; rit < myarray.crend(); ++rit )

    std::cout << ' ' << *rit;   // cannot modify *rit

 

  std::cout << '\n';

 

  return 0;

}

// array::data#include <iostream>#include <cstring>#include <array>

int main ()

{

  const char* cstr = "Test string";

  std::array<char,12> charray;

 

  std::memcpy (charray.data(),cstr,12);

 

  std::cout << charray.data() << '\n';

 

  return 0;

}

// array::empty#include <iostream>#include <array>

int main ()

{

  std::array<int,0> first;

  std::array<int,5> second;

  std::cout << "first " << (first.empty() ? "is empty" : "is not empty") << '\n';//返回是

  std::cout << "second " << (second.empty() ? "is empty" : "is not empty") << '\n';//返回否

  return 0;

}

// array::fill example#include <iostream>#include <array>

int main () {

  std::array<int,6> myarray;

 

  myarray.fill(5);

 

  std::cout << "myarray contains:";

  for ( int& x : myarray) { std::cout << ' ' << x; }

 

  std::cout << '\n';

 

  return 0;

}

// array::front#include <iostream>#include <array>

int main ()

{

  std::array<int,3> myarray = {2, 16, 77};

 

  std::cout << "front is: " << myarray.front() << std::endl;   // 2

  std::cout << "back is: " << myarray.back() << std::endl;     // 77

 

  myarray.front() = 100;

 

  std::cout << "myarray now contains:";

  for ( int& x : myarray ) std::cout << ' ' << x;

 

  std::cout << '\n';

 

  return 0;

}

// array::max_size#include <iostream>#include <array>

int main ()

{

  std::array<int,10> myints;

  std::cout << "size of myints: " << myints.size() << '\n';

  std::cout << "max_size of myints: " << myints.max_size() << '\n';

 

  return 0;

}

// array::operator[]#include <iostream>#include <array>

int main ()

{

  std::array<int,10> myarray;

  unsigned int i;

 

  // assign some values:

  for (i=0; i<10; i++) myarray[i]=i;

 

  // print content

  std::cout << "myarray contains:";

  for (i=0; i<10; i++)

    std::cout << ' ' << myarray[i];

  std::cout << '\n';

 

  return 0;

}

// array::rbegin/rend#include <iostream>#include <array>

int main ()

{

  std::array<int,4> myarray = {4, 26, 80, 14} ;

 

  std::cout << "myarray contains:";

  for ( auto rit=myarray.rbegin() ; rit < myarray.rend(); ++rit )

    std::cout << ' ' << *rit;

 

  std::cout << '\n';

 

  return 0;

}

// array::size#include <iostream>#include <array>

int main ()

{

  std::array<int,5> myints;

  std::cout << "size of myints: " << myints.size() << std::endl;

  std::cout << "sizeof(myints): " << sizeof(myints) << std::endl;

 

  return 0;

}

// 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;

}

// arrays as tuples#include <iostream>#include <array>#include <tuple>

int main ()

{

  std::array<int,3> myarray = {10, 20, 30};

  std::tuple<int,int,int> mytuple (10, 20, 30);

 

  std::tuple_element<0,decltype(myarray)>::type myelement;  // int myelement

 

  myelement = std::get<2>(myarray);

  std::get<2>(myarray) = std::get<0>(myarray);

  std::get<0>(myarray) = myelement;

 

  std::cout << "first element in myarray: " << std::get<0>(myarray) << "\n";

  std::cout << "first element in mytuple: " << std::get<0>(mytuple) << "\n";

 

  return 0;

}

// array comparisons#include <iostream>#include <array>

int main ()

{

  std::array<int,5> a = {10, 20, 30, 40, 50};

  std::array<int,5> b = {10, 20, 30, 40, 50};

  std::array<int,5> c = {50, 40, 30, 20, 10};

 

  if (a==b) std::cout << "a and b are equal\n";

  if (b!=c) std::cout << "b and c are not equal\n";

  if (b<c) std::cout << "b is less than c\n";

  if (c>b) std::cout << "c is greater than b\n";

  if (a<=b) std::cout << "a is less than or equal to b\n";

  if (a>=b) std::cout << "a is greater than or equal to b\n";

 

  return 0;

}

// deque::assign#include <iostream>#include <deque>

int main ()

{

  std::deque<int> first;

  std::deque<int> second;

  std::deque<int> third;

 

  first.assign (7,100);             // 7 ints with a value of 100

 

  std::deque<int>::iterator it;

  it=first.begin()+1;

 

  second.assign (it,first.end()-1); // the 5 central values of first

 

  int myints[] = {1776,7,4};

  third.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';

  std::cout << "Size of third: " << int (third.size()) << '\n';

  return 0;

}

 

// erasing from deque#include <iostream>#include <deque>

int main ()

{

  std::deque<int> mydeque;

 

  // set some values (from 1 to 10)

  for (int i=1; i<=10; i++) mydeque.push_back(i);

 

  // erase the 6th element

  mydeque.erase (mydeque.begin()+5);

 

  // erase the first 3 elements:

  mydeque.erase (mydeque.begin(),mydeque.begin()+3);

 

  std::cout << "mydeque contains:";

  for (std::deque<int>::iterator it = mydeque.begin(); it!=mydeque.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

// deque::get_allocator#include <iostream>#include <deque>

int main ()

{

  std::deque<int> mydeque;

  int * p;

  unsigned int i;

 

  // allocate an array with space for 5 elements using deque's allocator:

  p = mydeque.get_allocator().allocate(5);

 

  // construct values in-place on the array:

  for (i=0; i<5; i++) mydeque.get_allocator().construct(&p[i],i);

 

  std::cout << "The allocated array contains:";

  for (i=0; i<5; i++) std::cout << ' ' << p[i];

  std::cout << '\n';

 

  // destroy and deallocate:

  for (i=0; i<5; i++) mydeque.get_allocator().destroy(&p[i]);

  mydeque.get_allocator().deallocate(p,5);

 

  return 0;

}

 

// assignment operator with deques#include <iostream>#include <deque>

int main ()

{

  std::deque<int> first (3);    // deque with 3 zero-initialized ints

  std::deque<int> second (5);   // deque with 5 zero-initialized ints

 

  second = first;

  first = std::deque<int>();

 

  std::cout << "Size of first: " << int (first.size()) << '\n';

  std::cout << "Size of second: " << int (second.size()) << '\n';

  return 0;

}

 

// inserting into a deque#include <iostream>#include <deque>#include <vector>

int main ()

{

  std::deque<int> mydeque;

 

  // set some initial values:

  for (int i=1; i<6; i++) mydeque.push_back(i); // 1 2 3 4 5

 

  std::deque<int>::iterator it = mydeque.begin();

  ++it;

 

  it = mydeque.insert (it,10);                  // 1 10 2 3 4 5

  // "it" now points to the newly inserted 10

 

  mydeque.insert (it,2,20);                     // 1 20 20 10 2 3 4 5

  // "it" no longer valid!

 

  it = mydeque.begin()+2;

 

  std::vector<int> myvector (2,30);

  mydeque.insert (it,myvector.begin(),myvector.end());

                                                // 1 20 30 30 20 10 2 3 4 5

 

  std::cout << "mydeque contains:";

  for (it=mydeque.begin(); it!=mydeque.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

// deque::shrink_to_fit#include <iostream>#include <deque>

int main ()

{

  std::deque<int> mydeque (100);

  std::cout << "1. size of mydeque: " << mydeque.size() << '\n';

 

  mydeque.resize(10);

  std::cout << "2. size of mydeque: " << mydeque.size() << '\n';

 

  mydeque.shrink_to_fit();

 

  return 0;

}

// deque::emplace_from#include <iostream>#include <deque>

int main ()

{

  std::deque<int> mydeque = {10,20,30};

 

  mydeque.emplace_back (100);

  mydeque.emplace_back (200);

 

  std::cout << "mydeque contains:";

  for (auto& x: mydeque)

    std::cout << ' ' << x;

  std::cout << '\n';

 

  return 0;

}

// deque::emplace_from#include <iostream>#include <deque>//向前逐一添加元素

int main ()

{

  std::deque<int> mydeque = {10,20,30};

 

  mydeque.emplace_front (111);

  mydeque.emplace_front (222);

 

  std::cout << "mydeque contains:";

  for (auto& x: mydeque)

    std::cout << ' ' << x;

  std::cout << '\n';

 

  return 0;

}

// clearing deques#include <iostream>#include <deque>

int main ()

{

  unsigned int i;

  std::deque<int> mydeque;

  mydeque.push_back (100);

  mydeque.push_back (200);

  mydeque.push_back (300);

 

  std::cout << "mydeque contains:";

  for (std::deque<int>::iterator it = mydeque.begin(); it!=mydeque.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  mydeque.clear();//清除元素

  mydeque.push_back (1101);

  mydeque.push_back (2202);

 

  std::cout << "mydeque contains:";

  for (std::deque<int>::iterator it = mydeque.begin(); it!=mydeque.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

// swap deques#include <iostream>#include <deque>

 

main ()

{

  unsigned int i;

  std::deque<int> foo (3,100);   // three ints with a value of 100

  std::deque<int> bar (5,200);   // five ints with a value of 200

 

  foo.swap(bar);

 

  std::cout << "foo contains:";

  for (std::deque<int>::iterator it = foo.begin(); it!=foo.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  std::cout << "bar contains:";

  for (std::deque<int>::iterator it = bar.begin(); it!=bar.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

// 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;

}

// list::unique#include <iostream>#include <cmath>#include <list>

// a binary predicate implemented as a function:bool same_integral_part (double first, double second)

{ return ( int(first)==int(second) ); }

// a binary predicate implemented as a class:struct is_near {

  bool operator() (double first, double second)

  { return (fabs(first-second)<5.0); }

};

int main ()

{

  double mydoubles[]={ 12.15,  2.72, 73.0,  12.77,  3.14,

                       12.77, 73.35, 72.25, 15.3,  72.25 };

  std::list<double> mylist (mydoubles,mydoubles+10);

  

  mylist.sort();             //  2.72,  3.14, 12.15, 12.77, 12.77,

                             // 15.3,  72.25, 72.25, 73.0,  73.35

 

  mylist.unique();           //  2.72,  3.14, 12.15, 12.77

                             // 15.3,  72.25, 73.0,  73.35

 

  mylist.unique (same_integral_part);  //  2.72,  3.14, 12.15

                                       // 15.3,  72.25, 73.0

 

  mylist.unique (is_near());           //  2.72, 12.15, 72.25

 

  std::cout << "mylist contains:";

  for (std::list<double>::iterator it=mylist.begin(); it!=mylist.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

// splicing lists#include <iostream>#include <list>

int main ()

{

  std::list<int> mylist1, mylist2;

  std::list<int>::iterator it;

 

  // set some initial values:

  for (int i=1; i<=4; ++i)

     mylist1.push_back(i);      // mylist1: 1 2 3 4

 

  for (int i=1; i<=3; ++i)

     mylist2.push_back(i*10);   // mylist2: 10 20 30

 

  it = mylist1.begin();

  ++it;                         // points to 2

 

  mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4

                                // mylist2 (empty)

                                // "it" still points to 2 (the 5th element)

                                          

  mylist2.splice (mylist2.begin(),mylist1, it);

                                // mylist1: 1 10 20 30 3 4

                                // mylist2: 2

                                // "it" is now invalid.

  it = mylist1.begin();

  std::advance(it,3);           // "it" points now to 30

 

  mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());

                                // mylist1: 30 3 4 1 10 20

 

  std::cout << "mylist1 contains:";

  for (it=mylist1.begin(); it!=mylist1.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  std::cout << "mylist2 contains:";

  for (it=mylist2.begin(); it!=mylist2.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

// list::sort#include <iostream>#include <list>#include <string>#include <cctype>

// comparison, not case sensitive.bool compare_nocase (const std::string& first, const std::string& second)

{

  unsigned int i=0;

  while ( (i<first.length()) && (i<second.length()) )

  {

    if (tolower(first[i])<tolower(second[i])) return true;

    else if (tolower(first[i])>tolower(second[i])) return false;

    ++i;

  }

  return ( first.length() < second.length() );

}

int main ()

{

  std::list<std::string> mylist;

  std::list<std::string>::iterator it;

  mylist.push_back ("one");

  mylist.push_back ("two");

  mylist.push_back ("Three");

 

  mylist.sort();

 

  std::cout << "mylist contains:";

  for (it=mylist.begin(); it!=mylist.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  mylist.sort(compare_nocase);

 

  std::cout << "mylist contains:";

  for (it=mylist.begin(); it!=mylist.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

 

// remove from list#include <iostream>#include <list>

int main ()

{

  int myints[]= {17,89,7,14};

  std::list<int> mylist (myints,myints+4);

 

  mylist.remove(89);

 

  std::cout << "mylist contains:";

  for (std::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

 

// list::remove_if#include <iostream>#include <list>

// a predicate implemented as a function:bool single_digit (const int& value) { return (value<10); }

// a predicate implemented as a class:struct is_odd {

  bool operator() (const int& value) { return (value%2)==1; }

};

int main ()

{

  int myints[]= {15,36,7,17,20,39,4,1};

  std::list<int> mylist (myints,myints+8);   // 15 36 7 17 20 39 4 1

 

  mylist.remove_if (single_digit);           // 15 36 17 20 39

 

  mylist.remove_if (is_odd());               // 36 20

 

  std::cout << "mylist contains:";

  for (std::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)

    std::cout << ' ' << *it;

  std::cout << '\n';

 

  return 0;

}

 

// 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;

}

// 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;

}

// 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;

}

alpha: 10

beta: 20

gamma: 30

// map::lower_bound/upper_bound#include <iostream>#include <map>

int main ()

{

  std::map<char,int> mymap;

  std::map<char,int>::iterator itlow,itup;

 

  mymap['a']=20;

  mymap['b']=40;

  mymap['c']=60;

  mymap['d']=80;

  mymap['e']=100;

 

  itlow=mymap.lower_bound ('b');  // itlow points to b

  itup=mymap.upper_bound ('d');   // itup points to e (not d!)

 

  mymap.erase(itlow,itup);        // erases [itlow,itup)

 

  // print content:

  for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)

    std::cout << it->first << " => " << it->second << '\n';

 

  return 0;

}

a => 20

e => 100

// map::count#include <iostream>#include <map>

int main ()

{

  std::map<char,int> mymap;

  char c;

 

  mymap ['a']=101;

  mymap ['c']=202;

  mymap ['f']=303;

 

  for (c='a'; c<'h'; c++)

  {

    std::cout << c;

    if (mymap.count(c)>0)

      std::cout << " is an element of mymap.\n";

    else 

      std::cout << " is not an element of mymap.\n";

  }

 

  return 0;

}

a is an element of mymap.

b is not an element of mymap.

c is an element of mymap.

d is not an element of mymap.

e is not an element of mymap.

f is an element of mymap.

g is not an element of mymap

// map::equal_range#include <iostream>#include <map>

int main ()

{

  std::map<char,int> mymap;

 

  mymap['a']=10;

  mymap['b']=20;

  mymap['c']=30;

 

  std::pair<std::map<char,int>::iterator,std::map<char,int>::iterator> ret;

  ret = mymap.equal_range('b');

 

  std::cout << "lower bound points to: ";

  std::cout << ret.first->first << " => " << ret.first->second << '\n';

 

  std::cout << "upper bound points to: ";

  std::cout << ret.second->first << " => " << ret.second->second << '\n';

 

  return 0;

}

 

// map::key_comp#include <iostream>#include <map>

int main ()

{

  std::map<char,int> mymap;

 

  std::map<char,int>::key_compare mycomp = mymap.key_comp();

 

  mymap['a']=100;

  mymap['b']=200;

  mymap['c']=300;

 

  std::cout << "mymap contains:\n";

 

  char highest = mymap.rbegin()->first;     // key value of last element

 

  std::map<char,int>::iterator it = mymap.begin();

  do {

    std::cout << it->first << " => " << it->second << '\n';

  } while ( mycomp((*it++).first, highest) );

 

  std::cout << '\n';

 

  return 0;

}

// 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;

}

elements in mymap:

a => 50

c => 150

d => 200

// map::value_comp#include <iostream>#include <map>

int main ()

{

  std::map<char,int> mymap;

 

  mymap['x']=1001;

  mymap['y']=2002;

  mymap['z']=3003;

 

  std::cout << "mymap contains:\n";

 

  std::pair<char,int> highest = *mymap.rbegin();          // last element

 

  std::map<char,int>::iterator it = mymap.begin();

  do {

    std::cout << it->first << " => " << it->second << '\n';

  } while ( mymap.value_comp()(*it++, highest) );

 

  return 0;

}

// queue::back#include <iostream>       // std::cout#include <queue>          // std::queue

int main ()

{

  std::queue<int> myqueue;

 

  myqueue.push(12);

  myqueue.push(75);   // this is now the back

 

  myqueue.back() -= myqueue.front();

 

  std::cout << "myqueue.back() is now " << myqueue.back() << '\n';

 

  return 0;

}

// queue::emplace#include <iostream>       // std::cin, std::cout#include <queue>          // std::queue#include <string>         // std::string, std::getline(string)

int main ()

{

  std::queue<std::string> myqueue;

 

  myqueue.emplace ("First sentence");

  myqueue.emplace ("Second sentence");

 

  std::cout << "myqueue contains:\n";

  while (!myqueue.empty())

  {

    std::cout << myqueue.front() << '\n';

    myqueue.pop();

  }

 

  return 0;

}

// queue::empty#include <iostream>       // std::cout#include <queue>          // std::queue

int main ()

{

  std::queue<int> myqueue;

  int sum (0);

 

  for (int i=1;i<=10;i++) myqueue.push(i);

 

  while (!myqueue.empty())

  {

     sum += myqueue.front();

     myqueue.pop();

  }

 

  std::cout << "total: " << sum << '\n';

 

  return 0;

}

// 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;

}

// queue::size#include <iostream>       // std::cout#include <queue>          // std::queue

int main ()

{

  std::queue<int> myints;

  std::cout << "0. size: " << myints.size() << '\n';

 

  for (int i=0; i<5; i++) myints.push(i);

  std::cout << "1. size: " << myints.size() << '\n';

 

  myints.pop();

  std::cout << "2. size: " << myints.size() << '\n';

 

  return 0;

}

// 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;

}

// stack::emplace#include <iostream>       // std::cin, std::cout#include <stack>          // std::stack#include <string>         // std::string, std::getline(string)

int main ()

{

  std::stack<std::string> mystack;

 

  mystack.emplace ("First sentence");

  mystack.emplace ("Second sentence");

 

  std::cout << "mystack contains:\n";

  while (!mystack.empty())

  {

    std::cout << mystack.top() << '\n';

    mystack.pop();

  }

 

  return 0;

}

 

// stack::top#include <iostream>       // std::cout#include <stack>          // std::stack

int main ()

{

  std::stack<int> mystack;

 

  mystack.push(10);

  mystack.push(20);

 

  mystack.top() -= 5;

 

  std::cout << "mystack.top() is now " << mystack.top() << '\n';

 

  return 0;

}

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值