zoukankan      html  css  js  c++  java
  • C++ STL Vector

    今天听广播, 很喜欢一句话:拿自己的努力、勇气和泪水赌一份不保证实现的理想, 未来是不可预料的, 也正因为如此, 才充满无限可能;

    加油!!!

    涉及单词

    free 自由
    programmer 程序员
    worry 担心
    arbitrary 任意的 /'ɑːbɪt(rə)rɪ/
    container 容器
    performance 性能
    improve 提高
    program 程序
    hint 暗示, 提示
    constant 常数
    as 作为
    garbage 垃圾
    actually 实际上
    executed 执行
    increment 增加

    Vector constructors

    Syntax:

      #include <vector>
      vector();
      vector( const vector& c );
      vector( size_type num, const TYPE& val = TYPE() );
      vector( input_iterator start, input_iterator end );
      ~vector();

    The default vector constructor takes no arguments, creates a new instance of that vector.

    翻译:默认的向量构造函数不接受任何参数,从而创建该向量的新实例。

    The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c.

    翻译:第二个构造器是一个默认的复制构造函数,它可以用来创建一个新的向量,它是给定向量c的副本。

    The third constructor creates a vector with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:

    翻译:第三个构造函数为num对象创建一个带有空格的向量。如果val被指定,那么每个对象都将被赋予该值。例如,下面的代码创建了一个由5个整数42组成的向量:

    vector<int> v1( 5, 42 ); 

    The last constructor creates a vector that is initialized to contain the elements between start and end. For example:

    翻译:最后一个构造函数创建一个初始化的向量来包含起始和结束之间的元素。看例子:

     // create a vector of random integers
     cout << "original vector: ";
     vector<int> v;
     for( int i = 0; i < 10; i++ ) {
       int num = (int) rand() % 10;
       cout << num << " ";
       v.push_back( num );
     }
     cout << endl;            
    
     // find the first element of v that is even
     vector<int>::iterator iter1 = v.begin();
     while( iter1 != v.end() && *iter1 % 2 != 0 ) {
       iter1++;
     }              
    
     // find the last element of v that is even
     vector<int>::iterator iter2 = v.end();
     do {
       iter2--;
     } while( iter2 != v.begin() && *iter2 % 2 != 0 );              
    
     // only proceed if we find both numbers
     if( iter1 != v.end() && iter2 != v.begin() ) {
       cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;         
    
       cout << "new vector: ";
       vector<int> v2( iter1, iter2 );
       for( int i = 0; i < v2.size(); i++ ) {
         cout << v2[i] << " ";
       }
       cout << endl;
     }

    When run, this code displays the following output:

    翻译:在运行时,该代码显示以下输出:

     original vector: 1 9 7 9 2 7 2 1 9 8
     first even number: 2, last even number: 8
     new vector: 2 7 2 1 9       

    All of these constructors run in linear time except the first, which runs in constant time.

    翻译:所有这些构造函数都是线性时间,除了第一个,它在常数时间内运行。

    The default destructor is called when the vector should be destroyed.

    翻译:当矢量应该被销毁时,会调用默认的析构函数。

    Vector operators

    Syntax:

      #include <vector>
      TYPE& operator[]( size_type index );
      const TYPE& operator[]( size_type index ) const;
      vector operator=(const vector& c2);
      bool operator==(const vector& c1, const vector& c2);
      bool operator!=(const vector& c1, const vector& c2);
      bool operator<(const vector& c1, const vector& c2);
      bool operator>(const vector& c1, const vector& c2);
      bool operator<=(const vector& c1, const vector& c2);
      bool operator>=(const vector& c1, const vector& c2);

    All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a vector can be examined with the [] operator.

    翻译: 所有的C++容器都可以用标准的比较运算符来比较和分配: ==, !=, <=, >=, <, >, and =.。一个向量的个别元素可以用运算符来检验

    Performing a comparison or assigning one vector to another takes linear time. The [] operator runs in constant time.

    翻译: 执行一个比较或者指定一个vector 到另一个需要线性时间。 这个[ ] 运算符在常数时间内运行 

    Two vectors are equal if:

    翻译: 两个vector是相等的

      1. Their size is the same , and

      翻译: 他们的大小是相等的, 和

      2. Each member in location i in one vector is equal to the the member in location i in the other vector.

      翻译: 位置i中的每个元素都等于i在另一个向量中的位置i

    Comparisons among vectors are done lexicographically.

    翻译:矢量之间的比较是按字母顺序进行的

    For example, the following code uses the [ ] operator to access all of the elements  of  a vector:

    翻译: 例子: 下面代码使用[ ] 操作符从vector使用所有元素

     vector<int> v( 5, 1 );
     for( int i = 0; i < v.size(); i++ ) {
       cout << "Element " << i << " is " << v[i] << endl;
     }  

    assign

    Syntax:

      #include <vector>
      void assign( size_type num, const TYPE& val );
      void assign( input_iterator start, input_iterator end );

    The assign() [分配]function either gives the current vector  the values from start to end, or gives it num copies of val .

    翻译: assign()函数要么给定从start到end的值到vector, 要么给它num拷贝的值

    This function will destory the previous contents of the vector.

    翻译: 这个函数将要破坏vector的前一个内容

    For example , the following code uses assign() to put 10 copies of the integer 42 into a vector:

    翻译: 例子, 下面代码使用assign()将10个整数42复制放入到vector中

     vector<int> v;
     v.assign( 10, 42 );
     for( int i = 0; i < v.size(); i++ ) {
       cout << v[i] << " ";
     }
     cout << endl;

    The above code displays the following output:

    翻译:上面代码将显示下面的值

    42 42 42 42 42 42 42 42 42 42

    The next example shows how assign() can be used to copy one vector to another:

    翻译:下面例子显示assign()怎么将一个vector复制到另一个vector中

     vector<int> v1;
     for( int i = 0; i < 10; i++ ) {
       v1.push_back( i );
     }              
    
     vector<int> v2;
     v2.assign( v1.begin(), v1.end() );             
    
     for( int i = 0; i < v2.size(); i++ ) {
       cout << v2[i] << " ";
     }
     cout << endl;     

    When run, the above code displays the following output:

    翻译:运行上面代码显示下面结果

     0 1 2 3 4 5 6 7 8 9     

    at

    Syntax:

    #include<vector>
    TYPE& at(size_type loc );
    const TYPE& at( size_type loc ) const;

    The at() function returns a reference to the element in the vector at index loc. The at() function is safer than the [ ]operator, because it won't let you reference items outside the bounds of the vector.

    翻译:at()函数返回一个在索引loc中vector的参数引用。

       at()函数是一个安全的超过[ ] 操作符。因为它不允许引用vector边界之外的项。

    For example, consider the following code:

    翻译: 例子, 考虑下面的代码

    vector<int> v(5, 1);
    for (int i = 0; i < 10; i++){
      cout << "Element " << i << " is " << v[i] << endl;   
    }

    This  code overrunns the end of the vector , producing potentially dangerous results. The following code would be much safer:

    翻译: 这段代码覆盖了矢量的末端,产生了潜在的危险结果。下面代码将会更安全。

     vector<int> v( 5, 1 );
     for( int i = 0; i < 10; i++ ) {
       cout << "Element " << i << " is " << v.at(i) << endl;
     }  

    Instead of attempting to read garbage values from memory , the at()  function will realize that it is about to overrun the vector 

    and will throw an exception.

    翻译: at()函数不会尝试从内存中读取垃圾值,而是会意识到它即将溢出vector并抛出异常。

    back

    Syntax:

      #include <vector>
      TYPE& back();
      const TYPE& back() const;

    The back() function returns a reference to the last element in the vector.

    翻译:back()函数返回从vector中返回最后一个元素的引用。

    For example:

    翻译: 看例子

     vector<int> v;
     for( int i = 0; i < 5; i++ ) {
       v.push_back(i);
     }
     cout << "The first element is " << v.front()
          << " and the last element is " << v.back() << endl; 

    This code produces the following output:

    翻译: 这段代码产生下面输出

     The first element is 0 and the last element is 4  

    begin

    Syntax:

    #include<vector>
    iterator begin();
    const_iterator begin() const;

    The function begin() returns an iterator to the first element of the vector, and runs in constant time.

    翻译: begin()函数返回一个迭代器到vector的第一个元素, 运行为常数时间。

    For example, the following code uses begin() to initialize an iterator that is used to traverse the elements of a vector:

    翻译: 看例子, 下面代码使用begin()初始化一个迭代器,并使用它迭代遍历vector的元素。

    int vector_begin(){
        vector<string> words;
        string str;
        cout << "please input you content==>:" << '
    ';
        while (cin >> str){
            words.push_back(str);
            if (cin.get() == '
    '){
                break;
            }
        }
    
        vector<string>::iterator iter;
    
        for (iter =words.begin(); iter != words.end(); iter++){
            cout << *iter << '
    ';
        }
    
        return 0;
    }
    
    
    int main () {
    //    assign();
    
        vector_begin();
        return 0;
    }

    When given this input:

    翻译: 输入下面内容

    The last element in the vector;

    ...the above code produce the following output:

    翻译: 上面代码产生下面输出

    The
    last
    element
    in
    the
    vector;

    capacity

    Syntax:

    #include<vector>
    size_type capacity() const;

    The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space.

    翻译:这个captacity()函数返回vector参数数值 , 然后它需要分配更多内存

    For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size,

    the other method calls the reserve function to achieve a similar goal:

    翻译:例子, 下面代码使用不同方法设置capacity到两个vector中。 第一个方法通过传递到构造函数提示初始值大小, 另一个方法调用reserve函数达到相同目标

    int vector_capacity(){
        vector<int> v1(10);
    
        cout << "The capacity of v1 is : " << v1.capacity() << '
    ';
    
        vector<int> v2;
        v2.reserve(20);
        cout << "The capacity of v2 is : " << v2.capacity() << '
    ';
        return 0;
    }
    
    int main () {
        vector_capacity();
        return 0;
    }

    When run , the above code produces the following output:

    翻译: 运行上面代码的产生下面数据

    The capacity of v1 is 10
    The capacity of v2 is 20 

    但我觉得上面的那个例子不好, 官网有更好的例子

    // comparing size, capacity and max_size
    #include <iostream>
    #include <vector>
    
    int main ()
    {
      std::vector<int> myvector;
    
      // set some content in the vector:
      for (int i=0; i<100; i++) myvector.push_back(i);
    
      std::cout << "size: " << (int) myvector.size() << '
    ';
      std::cout << "capacity: " << (int) myvector.capacity() << '
    ';
      std::cout << "max_size: " << (int) myvector.max_size() << '
    ';
      return 0;
    }
    size: 100
    capacity: 128
    max_size: 1073741823

    官网的解释:

    分配存储容量的返回大小

    返回当前分配给vector的存储空间的大小,以元素的形式表示。

    这个容量不一定等于向量的大小。它可以是相等的,也可以是更大的,额外的空间允许在不需要重新分配的情况下适应增长。

    请注意,这个容量并不认为向量的大小是有限的。当这个容量耗尽并且需要更多的时候,它会被容器自动扩展(重新分配它的存储空间)。对vect的大小的理论限制

    C++ containers are designed to grow in size dynamically.This frees the programmer from havin to worry about storing an arbitrary number of elements in a container .

    However, sometimes the programmer can impove the performance of her program by giving hints to the compiler about the size of the containers that the program will use.

    These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.

    翻译: C++ 容器被设计成动态大小增长。 这样就可以让程序员不必担心在容器中存储任意数量的元素。

    然而, 有时程序员通过给编译器一些关于程序将要使用容易大小的提示来提高他们的程序性能。

    这些提示来自reserve()函数和使用上面例子构造函数, 告诉编译器预计获得多长

    The capacity() function runs in constant time.

    翻译: 这个capacity函数运行常数时间。

    clear

    Syntax:

    #include<vector>
    void clear();

    The function clear() deletes all of the elements in vector.

    clear() run in linear time.

    翻译: clear()函数删除vector内所有元素, 运行线性时间。

    empty

    Syntax:

    #include<vector>
    bool empty() const;

    The empty() function returns true if the vector has no elements, false otherwise.

    翻译: empty()函数返回true 如果vector没有元素, false则是有其他元素。

    For example, the following code uses empty() as the stoping condition on a while loop to clear a vector and display its contents in reverse order:

    翻译: 例子, 下面代码使用empty()作为while循环中的停止条件来清除一个矢量并以相反的顺序显示其内容

    int vector_empty(){
        vector<int> v;
        for (int i = 0; i < 5; i++){
            v.push_back(i);
        }
        cout << "The v empty status is :" << v.empty() << '
    ';
        while (!v.empty()){
            cout << v.back() << '
    ';
            v.pop_back();
        }
        cout << "The v empty status is :" << v.empty() << '
    ';
        return 0;
    }
    
    int main () {
        vector_empty();
        return 0;
    }

    When run , the above code produces following output:

    The v empty status is :0
    4
    3
    2
    1
    0
    The v empty status is :1

    end

    Syntax:

    #include <vector>
    iterator end();
    const_iterator end() const;

    The end() function returns an iterator just past the end of the vector.

    翻译: end()函数返回一个迭代器就在vector末端

    Note that before you can access the last element of the vector using an iterator that you get from a call to end(),

    you'll have to decrement the iterator first. This is because end() doesn't point to the end of the vector; it points just past the end of the vector.

    翻译: 请注意,在您可以使用从呼叫到结束()的迭代器访问vector的最后一个元素之前。

    你必须先缩减迭代器。 这是因为end()不能指向vector的末端; 它指向vector的末端--》我也表示很疑问。

    For example, in the following code, the first "cout" statement will display garbage, whereas the second statement will actually display the last element of the vector:

    翻译: 看例子, 里面代码, 第一个cout 语句将显示垃圾, 第二个语句实际上显示vector 最后一个元素

    int vector_end(){
        vector<int> v1;
        v1.push_back(5);
        v1.push_back(1);
        v1.push_back(2);
        v1.push_back(3);
    
        int bad_val = *(v1.end());
        cout << "bad_val is : " << bad_val << '
    ';
        int good_val = *(v1.end()-1);
        cout << "good_val is :" << good_val << '
    ';
        int begin_val = *(v1.begin());
        cout << "begin_val is : " << begin_val << '
    ';
    
    }
    
    int main () {
        vector_end();
        return 0;
    }

    The next example show how begin() and end() can be use to iterate through all of the members of a vector:

     翻译: 下一个例子查看begin() 和end() 函数将如何迭代vector所有成员。

    int vector_end(){
        vector<int> v2(5, 789);
        vector<int>::iterator it;
        for (it = v2.begin(); it != v2.end(); it++){
            cout << *it << endl;
        }
    }
    
    int main () {
        vector_end();
        return 0;
    }

    The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end().

    Since end()  returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.

     翻译: 迭代器初始化访问一个begin()。 在循环的主体被执行之后, 迭代器被递增并测试,以确定它是否等于调用end()的结果。

    第二个end()返回一个迭代器 在vector的最后一个元素之后指向一个元素 , 一旦所有的元素展示之后循环将会终止

    end() runs in constant time.

    翻译:end() 运行常数时间

    erase

    Syntax:

    #include<vector>
    iterator erase( iterator loc);
    iterator erase (iterator start, iterator end);

    The erase() function either deletes the element at location loc, or deletes the elements between start and end (including start but not including end);

    The return value is the element after the last element erased.

    翻译:erase()函数删掉本地loc, 或者删掉从开始到结束(包括开始但不包括结尾)之间的元素

    返回值是erased最后元素擦除后的元素

    The first version of erase(the version that deletes a single element at location loc) runs in constant time for list and linear time for vectors, dequeues, 

    and strings. The multiple-element version of erase always takes linear time.

    第一个函数是erase(在location loc中删除单个元素的版本)在常量时间内运行,用于列表和矢量、去队列和字符串的线性时间。

    For example:

    看例子:

    int vector_erase(){
    
        vector <char> alphaVector;
        for (int i = 0; i < 10; i++){
            alphaVector.push_back(i + 65);
        }
        int size = alphaVector.size();
    
        for (int j = 0; j < size; j++){
            cout << alphaVector[j];
        }
        cout << endl;
    
        vector<char>::iterator startIterator;
        vector<char>::iterator tempIterator;
        for (int i = 0; i < size; i++){
            startIterator = alphaVector.begin();
            alphaVector.erase(startIterator);
            
            cout << alphaVector.size() << endl;
    
            for (tempIterator = alphaVector.begin(); tempIterator != alphaVector.end(); tempIterator++){
                cout << *tempIterator;
            }
            cout << endl;
    
        }
        for (int j = 0; j < size; j++){
            cout << alphaVector[j];
        }
        cout << endl;
    
    
        return 0;
    }
    
    
    int main () {
        vector_erase();
        return 0;
    }

    That code would display the following output:

    ABCDEFGHIJ
    
    9
    BCDEFGHIJ
    8
    CDEFGHIJ
    7
    DEFGHIJ
    6
    EFGHIJ
    5
    FGHIJ
    4
    GHIJ
    3
    HIJ
    2
    IJ
    1
    J
    0
    
    JJJJJJJJJJ

    In the next example, erase() is called with two iterators to delete  a range of element from a vector:

    int vector_erase(){
    
        vector <char> alphaVector;
        for (int i = 0; i < 10; i++){
            alphaVector.push_back(i + 65);
        }
        int size = alphaVector.size();
    
        for (int j = 0; j < size; j++){
            cout << alphaVector[j];
        }
        cout << endl;
    
        alphaVector.erase(alphaVector.begin()+2, alphaVector.end()-3);
    
        for (int j = 0; j < size; j++){
            cout << alphaVector[j];
        }
        cout << endl;
    
    
        return 0;
    }
    
    
    int main () {
        vector_erase();
        return 0;
    }

    When run , the above code displays:

    ABCDEFGHIJ
    ABHIJFGHIJ

    front

    Syntax:

    #include<vector>
    TYPE& front();
    const TYPE& front() const;

    The front() function return a reference to the first of the vector, and runs in constant time.

    翻译: front()函数返回vector第一个元素的一个引用, 运行常数时间。

    For example, the following code use a vector and the sort() algorithm to display the first world (in alphabetical order) entered by a user:

    翻译: 看例子, 下面代码使用vector 和sort(按字母排序)算法显示用户输入的第一个单词

    #include <algorithm>

    int
    vector_front(){ vector<string> words; string str; while(cin >> str){ words.push_back(str); if (cin.get() == ' '){ break; } } sort(words.begin(), words.end()); cout << "In alphabetical order, the first word is' " << words.front() << " ' " << endl; return 0; } int main () { vector_front(); return 0; }

    When runs, the above code produces following output:

    wo shi ni daye
    In alphabetical order, the first word is' daye ' 

    insert

    Syntax:

    #include<vector>
    iterator insert (iterator loc, const TYPE& val);
    void insert (iterator loc, size_type num, const TYPE& val);
    template<TYPE> void insert (iterator loc, input_iterator start, input_iterator end);

    The insert() function either:

      1. inserts val before loc, returning an iterator to the element inserted, 

        在loc之前插入val,将迭代器返回到插入的元素

      2. inserts num copies of val before loc, or

        在loc之前插入val的副本,或者

      3. inserts the elements from start to end before loc.

        在loc之前将元素从开始到结束

    Note that inserting elements into a vector can be relatively time-intensive, since the underlying data structure for a vector is an array.

    注意,将元素插入到一个矢量中可能是相对时间密集型的, 因为矢量的底层数据结构是一个数组

    In order to insert data into an array, you might need to displace a lot of the elements of that array, and thsi can take linear time.

    为了将数据插入到一个数组中,您可能需要替换该阵列的许多元素,这可能需要线性时间。

    If you are planing on doing a lot of insertions into your vector and you care about speed, you might be better off using a container that has a linked list as its underlying data structure(such as a list or a Deque).

    如果您打算在您的vector中进行大量插入,并且关心速度,那么您最好使用一个具有链表作为其底层数据结构的容器(如列表或Deque)。

    For example, the  following code uses the inserts() function to splice four copies of the character 'C' into a vector of characters:

    例如,下面的代码使用insert()函数将字符C的四个副本拼接成一个字符的矢量:

    int vector_insert(){
        vector<char> alphaVector;
        for(int i = 0; i < 10; i++){
            alphaVector.push_back(i + 65);
    
        }
        vector<char>::iterator theIterator = alphaVector.begin();
        alphaVector.insert(theIterator, 6, 'C');
    
        for (theIterator=alphaVector.begin(); theIterator != alphaVector.end(); theIterator++){
            cout << *theIterator;
        }
        cout << endl;
        return 0;
    }
    
    int main () {
        vector_insert();
        return 0;
    }

    This code would display:

    CCCCCCABCDEFGHIJ

    Here is another example of the insert() function . In this code, insert() is used to append the contents of one vector onto the end of another:

    Insert() 函数的另一个例子, insert() 使用添加内容到另一个vector的末尾。

    int vector_insert_two(){
    
        vector<int> v1;
    
        v1.push_back( 0 );
        v1.push_back( 1 );
        v1.push_back( 2 );
        v1.push_back( 3 );
    
        vector<int> v2;
        v2.push_back( 5 );
        v2.push_back( 6 );
        v2.push_back( 7 );
        v2.push_back( 8 );
    
        cout << "Before, v2 is: ";
        for (int i = 0; i < v2.size(); i++){
            cout << v2[i] << " ";
        }
        cout << endl;
    
        v2.insert(v2.end(), v1.begin(), v1.end());
        cout << "After, v2 is: ";
    
        for (int i = 0; i < v2.size(); i++){
            cout << v2[i] << " ";
        }
        cout << endl;
        return 0;
    }
    
    int main () {
        vector_insert_two();
        return 0;
    }

    When run, this code displays:

    Before, v2 is: 5 6 7 8 
    After, v2 is: 5 6 7 8 0 1 2 3 

    max_size

    Syntax:

    #include<vector>
    size_type max_size() const;

    The max_size() function returns the maximum number of elements that the vector can hold. 

    The max_size() function should not be confused with the size() or capacity() functions, which return the number of elements currently in the vector 

    and the number of elements that the vector will be able to hold before more memory will have to be allocated, respectively.

    翻译:maxsize()函数返回vector所能容纳的最大元素数量。

    maxsize()函数不应该与size()或容量()函数混淆,后者返回当前vector中元素的数量,

    以及在需要分配更多内存之前,vector将能够容纳的元素数量。

    For example:

    int vector_max_size(){
    
        vector<int> v;
    
        cout << v.max_size()<< '
    ';
    
        return 0;
    }
    
    
    
    
    int main () {
        vector_max_size();
        return 0;
    }
    
    
    4611686018427387903

    pop_back

    Syntax:

    #include<vector>
    void pop_back();

    The pop_back() function removes the last elements of the vector

    pop_back() runs is constant time.

    For example:

    int vector_pop_back(){
        vector<int> v;
        for (int i = 0; i < 5; i++)
            v.push_back(i);
        for (int i = 0; i < v.size(); i++)
            cout << v[i] << ' ';
        cout << endl;
        v.pop_back();
        cout << v.size() << endl;
        for (int i = 0; i < v.size(); i++)
            cout << v[i] << ' ';
        cout << endl;
    
        return 0;
    }
    
    int main () {
        vector_pop_back();
        return 0;
    }
    
    0 1 2 3 4
    4
    0 1 2 3 

    push_back

    Syntax:

    #include <vector>
    void push_back( const TYPE& val);

    The push_back() function appends val to the end of the vector.

    For example , the following code puts 10 integers into a vector:

       vector<int> the_vector;
       for( int i = 0; i < 10; i++ ) {
         the_vector.push_back( i );
       }    

    When displayed, the resulting vector would look like this:

     0 1 2 3 4 5 6 7 8 9  

    push_back() runs in constant time.

    rbegin

    Syntax:

    #include <vector>
    reverse_iterator rbegin();
    const_reverse_iterator rbegin() const;

    The rbegin() function returns a reverse_iterator to the end of the current vector.

    rbegin() runs is constant time.

    看例子吧, 比较简单

    int vector_rbegin(){
    
    
        std::string str ("now step live...");
        cout << str << endl;
        for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
            std::cout << *rit;
    
    
        return 0;
    }
    
    
    int main () {
        vector_rbegin();
        return 0;
    }
    
    
    now step live...
    ...evil pets won

    rend

    Syntax:

    #include <vector>
    reverse_iterator rend();
    const_reverse_iterator rend() const;

    The function rend() a reverse_iterator to the begining of the current vector.

    rend() runs in constant time.

    代码同上

    reserve

    Syntax:

      #include <vector>
      void reserve( size_type size );

    看例子:

    不同于capacity

    int vector_reserve(){
        std::vector<int>::size_type sz;
    
        std::vector<int> foo;
        sz = foo.capacity();
        cout << sz << endl;
        std::cout << "making foo grow:
    ";
        for (int i=0; i<100; ++i) {
            foo.push_back(i);
    //        cout << sz << "<-->" << foo.capacity() << endl;
            if (sz!=foo.capacity()) {
                sz = foo.capacity();
                std::cout << "capacity changed: " << sz << '
    ';
            }
        }
    
        std::vector<int> bar;
        sz = bar.capacity();
        bar.reserve(100);   // this is the only difference with foo above
        std::cout << "making bar grow:
    ";
        for (int i=0; i<100; ++i) {
            bar.push_back(i);
            if (sz!=bar.capacity()) {
                sz = bar.capacity();
                std::cout << "capacity changed: " << sz << '
    ';
            }
        }
        return 0;
    }
    
    
    int main () {
        vector_reserve();
        return 0;
    }

    The reserve() function sets the capacity of the vector to at least size.

    reserve() runs in linear time.

    resize

    有点类似于指定size, 并指定填充内容, 如果没有指定则用0填充

    Syntax:

      #include <vector>
      void resize( size_type num, const TYPE& val = TYPE() );

     官方解释:

    对容器进行调整,使其包含n个元素。

    如果n比当前容器的大小要小,那么内容就会减少到它的第一个n个元素,将它们删除(并销毁它们)。

    如果n大于当前容器的大小,则通过在末端插入尽可能多的元素以达到n的大小来扩展内容,如果val被指定,新的元素被初始化为val的副本,否则,它们是初始化的。

    如果n也比当前的容器容量大,那么就会自动重新分配分配的存储空间。

    For example:

    int vector_resize(){
        std::vector<int> myvector;
    
        // set some initial content:
        for (int i=1;i<10;i++) myvector.push_back(i);
    
        for (int i=0; i < myvector.size(); i++)
            cout << myvector[i] << ' ';
        cout << endl;
    
        myvector.resize(5);
    
        for (int i=0; i < myvector.size(); i++)
            cout << myvector[i] << ' ';
        cout << endl;
    
        myvector.resize(8,100);
        
        for (int i=0; i < myvector.size(); i++)
            cout << myvector[i] << ' ';
        cout << endl;
    
        myvector.resize(12);
    
        std::cout << "myvector contains:";
        for (int i=0;i<myvector.size();i++)
            std::cout << ' ' << myvector[i];
        std::cout << '
    ';
        return 0;
    }
    
    int main () {
        vector_resize();
        return 0;
    }
    
    
    1 2 3 4 5 6 7 8 9
    1 2 3 4 5
    1 2 3 4 5 100 100 100
    myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0

    size

    vector<int> v;
    v.size();

    swap

    交互

    Syntax:

    #include <vector>
    void swap( container& from);

    The swap() function exchanges the elements of the current vector with those of from. This function operates in constant time.

    翻译: swap()函数将当前矢量的元素与来自于的元素交换。这个函数在恒定的时间内运行。

    For example, the following code uses the swap() function to exchange the contents of two vectors:

    翻译: 例如,下面的代码使用swap()函数来交换两个向量的内容:

    void print(vector<string> arg){
        vector<string>::iterator iter;
        for (iter=arg.begin(); iter != arg.end(); iter++){
            cout << *iter;
        }
        cout << endl;
    }
    
    int vector_swap(){
        vector<string>v1;
        v1.push_back("I'm in v1!");
    
        vector<string>v2;
        v2.push_back("I'm in v2!");
    
        v1.swap(v2);
    
        cout << "v1 is " << v1.front() << endl;
    
        print(v1);
    
        cout << "v2 is " << v2.front() << endl;
    
        print(v2);
    
    
        return 0;
    }
    
    
    int main () {
        vector_swap();
        return 0;
    }
    
    
    v1 is I'm in v2!
    I'm in v2!
    v2 is I'm in v1!
    I'm in v1!
  • 相关阅读:
    9.1做JS的题目(2)
    9.1做JS的题目
    8.31做JS的题目
    8.30做JS的题目
    扫码跳转微信小程序(服务端微信API生成二维码)
    扫码跳转微信小程序(微信公众平台配置测试二维码)
    项目配置:maven下载与配置、tomcat下载与配置
    Java基础:常用工具_API
    Java基础: 抽象类、接口、final关键字、static关键字
    java基础: 封装、继承、多态
  • 原文地址:https://www.cnblogs.com/renfanzi/p/9376856.html
Copyright © 2011-2022 走看看