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.
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.
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
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
Array | Vector | |
---|---|---|
Fixed | Dynamic | |
Need to specify the size | No need Specify size | |
Use myArray[index] | Use myVector.push_back() | |
Use delete[] myArray; | Use myVector.erase() |
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; }
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; }
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!