vector详细说明

        vector是一个线性顺序结构。相当于数组,但其大小可以不预先指定,并且自动扩展。它可以像数组一样被操作,由于它的特性我们完全可以将vector 看作动态数组。

1、构造函数

std::vector<int> first;               // 构造空vector
std::vector<int> second (4,100);      //构造一个包含4个值为100的vector
std::vector<int> third (second.begin(),second.end());// iterating through second
std::vector<int> fourth (third);      //复制构造函数

示例:

int constructorTest()
{
    std::vector<int> first;                                // empty vector of ints
    std::vector<int> second (4,100);                       // four ints with value 100
    std::vector<int> third (second.begin(),second.end());  // iterating through second
    std::vector<int> fourth (third);                       // a copy of third

    // the iterator constructor can also be used to construct from arrays:
    int myints[] = {16,2,77,29};
    std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

    std::cout << "The contents of fifth are:";
    for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    std::cout << "The contents of second are:";
    for (std::vector<int>::iterator it = second.begin(); it != second.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    std::cout << "The contents of third are:";
    for (std::vector<int>::iterator it = third.begin(); it != third.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    std::cout << "The contents of fourth are:";
    for (std::vector<int>::iterator it = fourth.begin(); it != fourth.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    return 0;
}

执行结果:

The contents of fifth are: 16 2 77 29
The contents of second are: 100 100 100 100
The contents of third are: 100 100 100 100
The contents of fourth are: 100 100 100 100

2、operator=

示例:

int operatorTest()
{
    std::vector<int> foo (3,100);
    std::vector<int> bar (5,100);

    bar = foo;
    foo = std::vector<int>();

    std::cout << "Size of foo: " << int(foo.size()) << '\n';
    std::cout << "The contents of foo are:";
    for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    std::cout << "Size of bar: " << int(bar.size()) << '\n';
    std::cout << "The contents of bar are:";
    for (std::vector<int>::iterator it = bar.begin(); it != bar.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    return 0;
}

执行结果:

Size of foo: 0
The contents of foo are:
Size of bar: 3
The contents of bar are: 100 100 100

3、Iterators

begin():返回第一个元素的迭代器

end():返回最末元素的迭代器

rbegin():返回Vector尾部的逆迭代器

rend():返回Vector起始的逆迭代器

cbegin():返回 constbegin()

cend():返回 constend()

crbegin():返回 constrbegin()

crend():返回 constrend()

示例:

int begin_end()
{
    std::vector<int> vec{1,2,3,4,5};

    for (std::vector<int>::iterator iter=vec.begin(); iter!=vec.end(); ++iter){
        std::cout << "old element:" << *iter;				// 打印元素
        (*iter) += 1;										// 通过迭代器修改对应元素
        std::cout << ", new:" << *iter << std::endl;

    }
    std::cout << "cbegin:";
    for (std::vector<int>::const_iterator iter=vec.cbegin(); iter!=vec.cend(); ++iter){
        std::cout << " " << *iter;
    }
    std::cout << "\n";
    std::cout << "rbegin:";
    for (std::vector<int>::reverse_iterator r_iter = vec.rbegin();         // 迭代器指向最后一个元素
         r_iter != vec.rend();          // rend() 指向第一个元素的前一个
         ++r_iter)	
    {
        std::cout << *r_iter << " ";    // prints 9,8,7,...0
        (*r_iter)++;
    }
    std::cout << "\n";
    std::cout << "crbegin:";				 
    for (std::vector<int>::const_reverse_iterator r_iter = vec.crbegin();         // 迭代器指向最后一个元素
         r_iter != vec.crend();          // rend() 指向第一个元素的前一个
         ++r_iter)	
    {
        std::cout << *r_iter << " ";    // prints 9,8,7,...0
    }    
    std::cout << "\n";
    return 0;
}

运行结果:

old element:1, new:2
old element:2, new:3
old element:3, new:4
old element:4, new:5
old element:5, new:6
cbegin: 2 3 4 5 6
rbegin:6 5 4 3 2 
crbegin:7 6 5 4 3

4、Capacity:

说明:

size(): 返回元素个数

max_size(): 返回vector最大能放元素个数

resize(): 调整容器大小,使其包含n个元素

capacity():返回以分配储存容量的大小

empty():容器是否为空

reserve():调整容器的容量大小

shrink_to_fit():减少容量适应其元素个数

示例:

int capacityTest()
{
    std::vector<int> myvector;
    for (int i=0; i<100; i++) 
        myvector.push_back(i);

    std::cout << "size: " << myvector.size() << "\n";
    std::cout << "capacity: " << myvector.capacity() << "\n";
    std::cout << "max_size: " << myvector.max_size() << "\n";

    myvector.resize(5);
    myvector.resize(8,100);
    myvector.resize(12);
    std::cout << "myvector contains:";
    for (int i=0;i<myvector.size();i++)
    std::cout << ' ' << myvector[i];
    std::cout << '\n';

    int sum (0);
    while (!myvector.empty())
    {
        sum += myvector.back();
        myvector.pop_back();
    }
    std::cout << "total: " << sum << '\n';

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

    myvector.resize(100,100);
    std::cout << "1. capacity of myvector: " << myvector.capacity() << ",size:" << myvector.size() << '\n';
    myvector.resize(10);
    std::cout << "2. capacity of myvector: " << myvector.capacity() << ",size:" << myvector.size() << '\n';

    myvector.shrink_to_fit();
    std::cout << "3. capacity of myvector: " << myvector.capacity() << ",size:" << myvector.size() << '\n';
    return 0;
}

运行结果:

size: 100
capacity: 128
max_size: 4611686018427387903
myvector contains: 0 1 2 3 4 100 100 100 0 0 0 0
total: 310
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 4
capacity changed: 8
capacity changed: 16
capacity changed: 32
capacity changed: 64
capacity changed: 128
making bar grow:
capacity changed: 100
capacity changed: 200
1. capacity of myvector: 128,size:100
2. capacity of myvector: 128,size:10
3. capacity of myvector: 10,size:10

5、元素操作

operator[]: 同数组方式取值

at():返回第n个元素的引用

front():返回第一个元素的引用

back():返回最后一个元素的引用

data():返回第一个元素的指针

示例:

int elementPro()
{
    std::vector<int> myvector (10);
    for (unsigned i=0; i<myvector.size(); i++) 
        myvector[i]=i;
    std::cout << "myvector contains:";
    for (unsigned i=0; i<myvector.size(); i++)
        std::cout << ' ' << myvector.at(i);
    std::cout << '\n';
    std::cout << "myvector.front(): " << myvector.front() << '\n';
    std::cout << "myvector.back(): " << myvector.back() << '\n';
    int* p = myvector.data();
    for (unsigned i=0; i<myvector.size(); i++)
    {
        *p = i*10;
        p++;
    }
    for (unsigned i=0; i<myvector.size(); i++)
        std::cout << ' ' << myvector.at(i);
    std::cout << '\n';
    return 0;
}

运行结果:

myvector contains: 0 1 2 3 4 5 6 7 8 9
myvector.front(): 0
myvector.back(): 9
 0 10 20 30 40 50 60 70 80 90

6、数据修改

assign():将新内容指定给向量,替换其当前内容,并相应修改其大小。

push_back():容器末尾增加一个元素

pop_back():容器末尾去掉一个元素 返回空

insert():插入一个元素 或系列元素,返回迭代器

erase():删除某个元素或者系列元素,返回迭代器

swap():交换容器内容

clear():清楚容器内所有元素

emplace():插入一个元素,每次只能插入一个元素,而不是多个

emplace_back():容器尾部添加一个元素

注:

1、push_bakc()添加元素时,首先会创建这个元素,然后再将这个元素拷贝或移动到容器中(如果是拷贝的话,事后会自行销毁之前创建的这个元素);emplace_back()添加元素时,则是直接在尾部创建这个元素,省去了拷贝或移动元素的过程。

2、insert() 函数有以下三种用法: 
1)在指定位置loc前插入值为val的元素,返回指向这个元素的迭代器
2)在指定位置loc前插入num个值为val的元素

3)在指定位置loc前插入区间[start, end)的所有元素

示例:

int changeTest()
{
    std::vector<int> first;
    first.assign (7,100);             // 7 ints with a value of 100
    std::cout << "first contains:";
    for (unsigned i=0; i<first.size(); i++)
        std::cout << ' ' << first.at(i);
    std::cout << '\n';

    std::vector<int> second(5);
    for (unsigned i=0; i<5; i++)
        second.push_back(i);
    std::cout << "after push second contains:";
    for (unsigned i=0; i<second.size(); i++)
        std::cout << ' ' << second.at(i);
    std::cout << '\n';
    for (unsigned i=0; i<5; i++)
        second.pop_back();
    std::cout << "after pop second contains:";
    for (unsigned i=0; i<second.size(); i++)
        std::cout << ' ' << second.at(i);
    std::cout << '\n';

    //insert 三种使用方法
    std::vector<int> myvector (3,100);
    std::vector<int>::iterator it;
    it = myvector.begin();
    it = myvector.insert (it, 200 );
    myvector.insert (it,2,300);
    std::cout << "after insert myvector contains:";
    for (it=myvector.begin(); it<myvector.end(); it++)
        std::cout << ' ' << *it;
    std::cout << '\n';
    it = myvector.begin();

    std::vector<int> anothervector (2,400);
    myvector.insert (it+2,anothervector.begin(),anothervector.end());
    int myarray [] = { 501,502,503 };
    myvector.insert (myvector.begin(), myarray, myarray+3);
    std::cout << "after insert2 myvector contains:";
    for (it=myvector.begin(); it<myvector.end(); it++)
        std::cout << ' ' << *it;
    std::cout << '\n';

    //erase 用法
    // erase the 6th element
    myvector.erase (myvector.begin()+5);
    // erase the first 3 elements:
    myvector.erase (myvector.begin(),myvector.begin()+3);
    std::cout << "after erase myvector contains:";
    for (unsigned i=0; i<myvector.size(); ++i)
        std::cout << ' ' << myvector[i];
    std::cout << '\n';

    //swap
    std::vector<int> foo (3,100);   // three ints with a value of 100
    std::vector<int> bar (5,200);   // five ints with a value of 200
    foo.swap(bar);
    std::cout << "foo contains:";
    for (unsigned i=0; i<foo.size(); i++)
        std::cout << ' ' << foo[i];
    std::cout << '\n';
    std::cout << "bar contains:";
    for (unsigned i=0; i<bar.size(); i++)
        std::cout << ' ' << bar[i];
    std::cout << '\n';

    foo.clear();
    std::cout << "after clear foo size:" << foo.size() << "\n";

    std::vector<int> emplace_vector = {10,20,30};
    it = emplace_vector.emplace ( emplace_vector.begin()+1, 100 );
    emplace_vector.emplace ( it, 200 );
    emplace_vector.emplace ( emplace_vector.end(), 300 );
    std::cout << "emplace_vector contains:";
    for (auto& x: emplace_vector)
        std::cout << ' ' << x;
    std::cout << '\n';

    emplace_vector.emplace_back (100);
    emplace_vector.emplace_back (200);
    std::cout << "after emplace_back emplace_vector contains:";
    for (auto& x: emplace_vector)
        std::cout << ' ' << x;
    std::cout << '\n';
    return 0;
}

运行结果:

first contains: 100 100 100 100 100 100 100
after push second contains: 0 0 0 0 0 0 1 2 3 4
after pop second contains: 0 0 0 0 0
after insert myvector contains: 300 300 200 100 100 100
after insert2 myvector contains: 501 502 503 300 300 400 400 200 100 100 100
after erase myvector contains: 300 300 400 200 100 100 100
foo contains: 200 200 200 200 200
bar contains: 100 100 100
after clear foo size:0
emplace_vector contains: 10 200 100 20 30 300
after emplace_back emplace_vector contains: 10 200 100 20 30 300 100 200

7、其他用法

get_allocator():返回与容器关联的分配器对象的副本

operators:

operationequivalent operation
a!=b!(a==b)
a>bb<a
a<=b!(b<a)
a>=b!(a<b)

示例

int otherTest()
{
    std::vector<int> myvector;
    int * p;
    // allocate an array with space for 5 elements using vector's allocator:
    p = myvector.get_allocator().allocate(5);
    // construct values in-place on the array:
    for (int i=0; i<5; i++) 
        myvector.get_allocator().construct(&p[i],i);
    std::cout << "The allocated array contains:";
    for (int i=0; i<5; i++) 
        std::cout << ' ' << p[i];
    std::cout << '\n';
    // destroy and deallocate:
    for (int i=0; i<5; i++) 
        myvector.get_allocator().destroy(&p[i]);
    myvector.get_allocator().deallocate(p,5);

    std::vector<int> foo (3,100);   // three ints with a value of 100
    std::vector<int> bar (3,100); 
    if(foo == bar) 
       std::cout << "foo and bar are equal\n"; 
    foo = {100,200};
    bar = {200};
    if(foo < bar) 
       std::cout << "foo less than bar\n"; 
    foo = {100,200};
    bar = {50};
    if(foo > bar) 
       std::cout << "foo biger than bar\n"; 
    foo = {100,200};
    bar = {100};
    if(foo > bar) 
       std::cout << "foo biger than bar\n";
}

运行结果

The allocated array contains: 0 1 2 3 4
foo and bar are equal
foo less than bar
foo biger than bar
foo biger than bar

C++ 中,vector 是一种动态数组,它可以在运行时动态地增加或减少其大小。Vector 中的元素是连续存储的,并且可通过索引访问。 在 C 语言中,并没有内置的 vector 类型。但是,我们可以通过手动分配内存来实现类似于 vector 的功能。具体来说,我们可以使用 malloc() 函数动态地分配内存,然后使用指针来访问数组中的元素。我们还可以使用 realloc() 函数来调整分配的内存块的大小。 下面是一个使用 C 语言实现类似于 vector 的示例代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct { int *data; int size; } vector; void vector_init(vector *v) { v->data = NULL; v->size = 0; } void vector_push_back(vector *v, int value) { v->data = realloc(v->data, sizeof(int) * (v->size + 1)); v->data[v->size++] = value; } int vector_at(vector *v, int index) { return v->data[index]; } void vector_free(vector *v) { free(v->data); v->data = NULL; v->size = 0; } int main() { vector v; vector_init(&v); vector_push_back(&v, 1); vector_push_back(&v, 2); vector_push_back(&v, 3); for (int i = 0; i < v.size; i++) { printf("%d ", vector_at(&v, i)); } printf("\n"); vector_free(&v); return 0; } ``` 在上面的代码中,我们首先定义了一个 vector 结构体,其中包含一个指向 int 型数组的指针和数组的大小。然后,我们使用 vector_init() 函数初始化 vector。接下来,我们使用 vector_push_back() 函数向 vector 中添加元素。vector_push_back() 函数会使用 realloc() 函数来调整 vector 的大小,并将新元素添加到 vector 的末尾。最后,我们使用 vector_at() 函数访问 vector 中的元素,并使用 vector_free() 函数释放 vector 占用的内存。 需要注意的是,由于 C 语言中没有异常处理机制,因此我们需要手动检查 malloc() 和 realloc() 函数是否成功分配了内存,并在失败时进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值