c++11 standard template (STL) std::vector (eight)

Defined in the header file <vector>
template<

    class T,
    class Allocator = std::allocator<T>

> class vector;
(1)
namespace pmr {

    template <class T>
    using vector = std::vector<T, std::pmr::polymorphic_allocator<T>>;

}
(2) (since C++17)

 1) std::vectoris a sequential container that encapsulates a dynamic array.

2) std::pmr::vectoris a template alias that uses a polymorphic allocator.

Elements are stored sequentially, which means that elements can be accessed not only through iterators, but also with regular pointers to elements. This means that a pointer to a vector element can be passed to any function expecting a pointer to an array element.

(since C++03)

The storage of vector is managed automatically, expanding and shrinking on demand. A vector typically takes up more space than a static array because more memory is allocated to manage future growth. The way the vector is used is not to reallocate every time an element is inserted, but only when the extra memory is exhausted. The total amount of memory allocated can be queried with the capacity() function. Additional memory can be returned to the system through a call to shrink_to_fit(). (since C++11)

Reallocation is usually a performance-intensive operation. The reserve() function can be used to eliminate reallocation if the number of elements is known.

The complexity (efficiency) of common operations on vector is as follows:

  • Random access - constant O(1)
  • Insert or remove elements at the end - amortized constant O(1)
  • Insert or remove elements - O(n) linear in distance to end of vector

std::vector(For boolother T) Satisfy the requirements of Container , AllocatorAwareContainer , SequenceContainer , ContiguousContainer (since C++17) and ReversibleContainer .

modifier

clear content

std::vector<T,Allocator>::clear

void clear();

(until C++11)

void clear() noexcept;

(since C++11)

 Erases all elements from the container. size() returns zero after this call.

Illegalizes any reference, pointer or iterator referring to the contained elements. Any post-end iterators are also invalidated.  

vectorLeave the capacity() of unchanged (note: the criteria for changing the capacity are limited vector::reserveby the specification of , see [1] ).

parameter

(none)

return value

(none)

the complexity

Linear with the size of the container, i.e. the number of elements.

erase element

std::vector<T,Allocator>::erase

iterator erase( iterator pos );

(1) (until C++11)

iterator erase( const_iterator pos );

(since C++11)

iterator erase( iterator first, iterator last );

(2) (until C++11)

iterator erase( const_iterator first, const_iterator last );

(since C++11)

 Erases the specified element from the container.

1) Remove the element posat .

2) Removes elements [first; last)in .

Illegalizes iterators at or after the erasure point, including end() iterators.

Iterators posmust be valid and dereferenceable. Thus cannot end() the iterator (legal, but not dereferenced) as the value posof .

If first==lastthen iterator firstneed not be dereferenceable: erasing an empty range is a no-op.

parameter

pos - iterator to the element to remove
first, last - range of elements to remove
type requirements
-Must Tmeet the requirements of MoveAssignable .

return value

Iterator following the last removed element. If iterator posrefers to the last element, returns the end() iterator.

abnormal

Does not throw unless the assignment operator Tof does throw.

the complexity

Linear: T's destructor is called as many times as the number of elements erased, and T's assignment operator is called as many times as the number of elements in vector after the erased element.

remove last element

std::vector<T,Allocator>::pop_back

void pop_back();

 Removes the last element of the container.

Calling on an empty container pop_backis undefined.

Illegalizes iterators and references to the end element, and end() iterators.

parameter

(none)

return value

(none)

the complexity

constant.

abnormal

(none)

exchange content

std::vector<T,Allocator>::swap

void swap( vector& other );

(before C++17)

void swap( vector& other ) noexcept(/* see below */);

(since C++17)

 Exchange the content with otherthe . Does not invoke any move, copy, or swap operations on individual elements.

All iterators and references remain valid. Post-end iterators are invalidated.

If std::allocator_traits<allocator_type>::propagate_on_container_swap::value is true, the allocator is swapped with a non- swapmember unqualified call. Otherwise, they are not swapped (and the behavior is undefined if get_allocator() != other.get_allocator() ).

(since C++11)

parameter

other - The container to exchange content with

return value

(none)

abnormal

(none)

(before C++17)
noexcept specifies:  

noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value
|| std::allocator_traits<Allocator>::is_always_equal::value)

(since C++17)

the complexity

constant.

call example

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <time.h>
#include <vector>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell() = default;
    Cell(int a, int b): x(a), y(b) {}

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator *(const Cell &cell)
    {
        x *= cell.x;
        y *= cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }


    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator >(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y > cell.y;
        }
        else
        {
            return x > cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}


int main()
{
    std::cout << std::boolalpha;

    std::mt19937 g{std::random_device{}()};
    srand((unsigned)time(NULL));

    auto generate = []()
    {
        int n = std::rand() % 10 + 110;
        Cell cell{n, n};
        return cell;
    };

    //3) 构造拥有 count 个有值 value 的元素的容器。
    std::vector<Cell> vector1(3, generate());
    //替换容器的内容。1) 以 count 份 value 的副本替换内容。
    std::cout << "vector1:  ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;

    //3) 构造拥有 count 个有值 value 的元素的容器。
    std::vector<Cell> vector2(5, {101, 101});
    //替换容器的内容。1) 以 count 份 value 的副本替换内容。
    std::cout << "vector2:  ";
    std::copy(vector2.begin(), vector2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;

    //将内容与 other 的交换。不在单个元素上调用任何移动、复制或交换操作。
    //所有迭代器和引用保持合法。尾后迭代器被非法化。
    std::cout << "swap before:" << std::endl;
    std::cout << "vector1:  ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "vector2:  ";
    std::copy(vector2.begin(), vector2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    vector1.swap(vector2);
    std::cout << "swap after:" << std::endl;
    std::cout << "vector1:  ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "vector2:  ";
    std::copy(vector2.begin(), vector2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;

    //从容器擦除所有元素。此调用后 size() 返回零。
    //非法化任何指代所含元素的引用、指针或迭代器。任何尾后迭代器亦被非法化。
    //保持 vector 的 capacity() 不变
    std::cout << "clear before:" << std::endl;
    std::cout << "vector2.size():       " << vector2.size() << std::endl;
    std::cout << "vector2.data():       " << vector2.data() << std::endl;
    vector2.clear();
    std::cout << "clear after:" << std::endl;
    std::cout << "vector2.size():       " << vector2.size() << std::endl;
    std::cout << "vector2.data():       " << vector2.data() << std::endl;
    std::cout << std::endl;


    std::vector<Cell> vector3(6, generate());
    std::generate(vector3.begin(), vector3.end(), generate);
    std::cout << "vector3:  ";
    std::copy(vector3.begin(), vector3.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    //从容器擦除指定的元素。1) 移除位于 pos 的元素。
    vector3.erase(vector3.begin());
    std::cout << "iterator erase( iterator pos ) after: " << std::endl;
    std::cout << "vector3:  ";
    std::copy(vector3.begin(), vector3.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    //从容器擦除指定的元素。2) 移除范围 [first; last) 中的元素。
    vector3.erase(vector3.begin() + 1, vector3.end() - 1);
    std::cout << "iterator erase( iterator pos ) after: " << std::endl;
    std::cout << "vector3:  ";
    std::copy(vector3.begin(), vector3.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;

    //移除容器的最末元素。在空容器上调用 pop_back 是未定义的。
    //非法化指向末元素的迭代器和引用,以及 end() 迭代器。
    vector3.pop_back();
    std::cout << "vector3:  ";
    std::copy(vector3.begin(), vector3.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}

output

 

Guess you like

Origin blog.csdn.net/qq_40788199/article/details/130463140