programs using vectors in c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Declare a vector of integers named 'numbers'
// Add elements to the vector using push_back()
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Access and print elements using []
std::cout << "Elements in the vector: ";
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
std::cout << "\n";
// Modify elements in the vector
numbers[1] = 50;
// Iterate through the vector using iterators
std::cout << "Modified elements using iterators: ";
for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
// Erase an element from the vector
numbers.erase(numbers.begin() + 2);
// Display the final elements in the vector
std::cout << "Final elements in the vector: ";
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << "\n";
return 0;
}
Explanation:
#include <iostream>
and#include <vector>
: Includes necessary libraries for input/output operations and vectors.std::vector<int> numbers;
: Declares a vector namednumbers
that holds integers.numbers.push_back(10);
,numbers.push_back(20);
,numbers.push_back(30);
: Adds elements (10, 20, 30) to the vector usingpush_back()
method.for (size_t i = 0; i < numbers.size(); ++i) { std::cout << numbers[i] << " "; }
: Iterates through the vector using indices and prints each element.numbers[1] = 50;
: Modifies the second element of the vector (index 1) and assigns it the value 50.for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << " "; }
: Iterates through the vector using iterators and prints each element.numbers.erase(numbers.begin() + 2);
: Erases the third element from the vector.for (const auto& num : numbers) { std::cout << num << " "; }
: Iterates through the vector using a range-based for loop and prints each element.