Listen
#include <iostream> #include <vector> int main() { // Array declaration and initialization int intArray[5] = {1, 2, 3, 4, 5}; // Accessing array elements std::cout << "Array elements:" << std::endl; for (int i = 0; i < 5; i++) { std::cout << "Element at index " << i << ": " << intArray[i] << std::endl; } // Vector declaration and initialization std::vector<int> intVector = {10, 20, 30, 40, 50}; // Accessing vector elements std::cout << "\nVector elements:" << std::endl; for (size_t i = 0; i < intVector.size(); i++) { std::cout << "Element at index " << i << ": " << intVector[i] << std::endl; } // Adding elements to the vector intVector.push_back(60); std::cout << "\nVector elements after adding a new element:" << std::endl; for (size_t i = 0; i < intVector.size(); i++) { std::cout << "Element at index " << i << ": " << intVector[i] << std::endl; } return 0; }
This code block demonstrates an example of arrays and vectors in C++. The program first declares and initializes an array called intArray
and then accesses its elements using a for loop. Then, it declares and initializes a vector called intVector
, accesses its elements using another for loop, and demonstrates how to add an element to a vector using push_back()
.