简体   繁体   中英

Size and resize function of vector container in c++

I don't understand the next behavior with the functions size() and resize() in my program.

I create a vector of structs with 3 elements.

In the last part of the code, I use the function resize() in order to have only 2 elements. Then I assign again values to 3 elements getting a 3-element vector.

In the last part I can call the 3 elements of the vector vector_a so I understand I have a 3-element vector but the function size() is giving me as an output that I have 2 elements.

// Example program
#include <iostream>
#include <vector>

int main()
{
    struct struct_1
    {
        int variable_1;
        int variable_2;
    };

    std::vector<struct_1> vector_a;

    vector_a.push_back(struct_1());
    vector_a.push_back(struct_1());
    vector_a.push_back(struct_1());

    vector_a.resize(2);


    vector_a[0].variable_1 = 21;
    vector_a[0].variable_2 = 34;

    vector_a[1].variable_1 = 111;
    vector_a[1].variable_2 = 764;

    vector_a[2].variable_1 = 5656;
    vector_a[2].variable_2 = 5666764;

    std::cout << "size    " << vector_a.size() << std::endl;
}

What am I missing?

The operator[] directly accesses memory and doesn't check for the bounds, so referencing index 2 while the size is only 2 is invalid.

A related problem sometimes seen in code is developers calling vector.reserve(10) and then indexing elements 0 to 9 (instead of reserve they should call resize ).

It looks like you wouldn't get exception out of range if you keep accessing elements in this way... try .at() method if you want to get exception.

A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

To add the previous answers

Then I assign again values to 3 elements getting a 3-element vector.

You are not, from cppreference the description of std::vector::operator[]

Returns a reference to the element at specified location pos. No bounds checking is performed.

This operator does not add an element to the vector if you are accessing an out of bound element (it is not like an std::map )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM