Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++ Vector #222

Open Qingquan-Li opened 1 year ago

Qingquan-Li commented 1 year ago

1. What is STL vector

Concept: The Standard Template Library offers a vector data type, which in many ways, is superior to standard arrays.

The Standard Template Library (STL) is a collection of data types and algorithms that you may use in your programs. These data types and algorithms are programmer-defined. They are not part of the C++ language, but were created in addition to the built-in data types.

A vector is a container that can store data. It is like an array in the following ways:

However, a vector offers several advantages over arrays. Here are just a few:

2. Defining a vector

Example:

#include <vector> // Must include the `<vector>` header file.

// Defines numbers as an empty vector of ints.
vector<int> numbers;
// The data type follows the word vector.
// No need to declare a size.

Because the vector expands in size as you add values to it, there is no need to declare a size. You can define a starting size, if you prefer:

vector<int> numbers(10);

When you specify a starting size for a vector, you may also specify an initialization value. The initialization value is copied to each element. Here is an example:

vector<int> numbers (10, 2);

In this statement, numbers is defined as a vector of 10 ints. Each element in numbers is initialized to the value 2.

You may also initialize a vector with the values in another vector. For example, look at the following statement. Assume set1 is a vector of ints that already has values stored in it.

vector<int> set2(set1);

After this statement executes, set2 will be a copy of set1.

3. Using an Initialization List with a vector in C++ 11

Example:

vector<int> numbers { 10, 20, 30, 40 };

This statement defines a vector of ints named numbers. The vector will have four elements, initialized with the values 10, 20, 30, 40. Notice the initialization list is enclosed in a set of braces, but you do not use an = operator before the list.

4. Using the Range-Based for Loop with a vector

The range-based for loop was introduced in C++ 11. With C++ 11, you can use a range-based for loop to step through the elements of a vector.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Define and initialize a vector.
    vector<int> vector_numbers { 10, 20, 30, 40, 50 };
    // Define and initialize an array.
    int array_numbers[] = { 60, 70, 80, 90, 100 };

    cout << "Display the vector elements: \n";
    for (int val : vector_numbers)
        cout << val << " ";
    cout << endl;

    cout << "\nDisplay the array elements:\n";
    for (int val : array_numbers)
        cout << val << " ";

    return 0;
}

Output:

Display the vector elements: 
10 20 30 40 50 
Display the array elements: 
60 70 80 90 100 

5. Growing a Vector's Size

Use the push_back member function to add an element to a vector. Elements are added to the back of the vector.

// Add a new element holding the value 75
scores.push_back(75);

Using the size member function to determine the number of elements currently in a vector:

int howBig = scores.size();

Example:

#include <iostream>
#include <vector>
using namespace std;

// Function prototype:
void showValues(vector<int>);

int main()
{
    vector<int> values;

    for (int count = 0; count < 7; count++)
        values.push_back(count * 2);

    showValues(values);

    return 0;
}

void showValues(vector<int> vect) {
    // for (int count : vect)
    //     cout << count << " ";
    for (int count = 0; count < vect.size(); count++)
        cout << vect[count] << " ";
}

Output:

0 2 4 6 8 10 12 

6. Removing Vector Elements

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Define and initialize a vector.
    vector<int> vector_numbers { 10, 20, 30, 40, 50 };

    // Use the `pop_back` member function to remove the last element from a vector.
    // Note: `pop_back` removes the last element but not return it.
    vector_numbers.pop_back();

    for (int count : vector_numbers)
        cout << count << " ";

    // To remove all of the elements from a vector, use the `clear` member function.
    vector_numbers.clear();

    // To determine if a vector is empty, use `empty` member function.
    if (vector_numbers.empty()) {
        cout << "\nvector_numbers is empty";
    }

    return 0;
}

Output:

10 20 30 40 
vector_numbers is empty

7. Other Useful Member Functions

Member Function Description Example
at(i) Returns the value of the element at position i in the vector cout << vec1.at(i);
capacity() Returns the maximum number of elements a vector can store without allocating more memory maxElements = vec1.capacity();
reverse() Reverse the order of the elements in a vector vec1.reverse();
resize(n)
or resize(n,val)
Resizes the vector so it contains n elements. If new elements are added, they are initialized to val vec1.resize(8,10);
swap(vec2) Exchange the contents of two vectors vec1.swap(vec2);