Home > Backend Development > C++ > What is the difference between arrays and vectors in C++?

What is the difference between arrays and vectors in C++?

WBOY
Release: 2024-06-02 12:25:58
Original
337 people have browsed it

In C++, an array is a fixed-size data structure whose size needs to be specified at creation time, while a vector is a dynamic-sized data structure whose size can be changed at runtime. Arrays use the [] operator to access and modify elements, while vectors use the push_back() method to add elements and the [] operator to access elements. Arrays need to use delete[] to release memory, while vectors use erase() to delete elements.

C++ 中的数组与向量有什么区别?

Arrays and Vectors in C++: Differences and Practical Combat

In C++, arrays and vectors are used to store the same A collection of type data. However, they have some key differences in how they create, access, and manage data.

Array

An array is a fixed-size data structure whose size is specified when it is created. Use the [] operator to access and modify elements in an array.

int myArray[5] = {1, 2, 3, 4, 5};

cout << myArray[2]; // 输出 3
myArray[3] = 10;  // 将元素 4 替换为 10
Copy after login

Vector

A vector is a dynamically sized data structure whose size can change at runtime. Use the push_back() method to add elements and the [] operator to access and modify elements.

vector<int> myVector; // 创建一个空向量

myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);

cout << myVector[1]; // 输出 2
myVector[2] = 10;  // 将元素 3 替换为 10
Copy after login

Difference

##CharacteristicsArrayVectorSizeFixedDynamicCreateNeed to specify the sizeNo need Specify sizeAdd elementsUse myArray[index]Use myVector.push_back()Delete elementUse delete[] myArray;Use myVector.erase()##Practical case

Calculate the average using an array

int main() {
    int myArray[5] = {1, 2, 3, 4, 5};

    int sum = 0;
    for (int i = 0; i < 5; i++) {
        sum += myArray[i];
    }

    double average = (double)sum / 5;

    cout << average << endl;

    return 0;
}
Copy after login

Use a vector to store student scores

int main() {
    vector<int> scores;

    scores.push_back(85);
    scores.push_back(90);
    scores.push_back(95);

    for (vector<int>::iterator it = scores.begin(); it != scores.end(); it++) {
        cout << *it << endl;
    }

    return 0;
}
Copy after login

The above is the detailed content of What is the difference between arrays and vectors in C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template