Vectors
C++ lists and C++ vectors are both in a family of structures called sequence containers. These containers allow you to store values in series and then access those values. C++ has a handful of sequence containers including lists, vectors, and arrays.
Declaring C++ Vectors
Including the Vector Library
In an actual program, you would need to include the vector file from the Standard Library:
Initializing Vector Values
In the previous part of the lesson, you learned to declare a vector first and then assign values:
There are various other ways for assigning initial values to a vector. Here are two other ways:
Declaring and Defining Simultaneously
When declaring a vector, you can also assign initial values simultaneously.
The code will declare a vector with ten elements, and each element will have the value 6.
Declaring and Defining Simultaneously with Brackets
There is another way to initialize a vector as well if you are using one of the more recent versions of C++ such as C++11 or C++17; You could also do something like:
The different versions of C++ (C++98, C++11, C++14, and C++17) will be discussed in the Practical C++ lesson.
vector<T>::size_type
is an implementation dependent type, which is usually size_t
. Since it isn't specified by the standard and could potentially change, you should prefer to use it when you are dealing with elements of that type. For example, the type of vector<T>::size()
returns a vector<T>::size_type
. Thus, if you are iterating over the vector
with an integral index, you would want this index to be of type vector<T>::size_type
. This will ensure that your code is easy to maintain - if you decide to use a different implementation of the standard library, your code will be consistent.
size_type
is a (static) member type of the type vector<int>
. Usually, it is a typedef
for std::size_t
, which itself is usually a typedef
for unsigned int
or unsigned long long
.
Last updated
Was this helpful?