BCA
Object Oriented Programming using C++ Practical
Madras University
Program 11
Demonstrate the use of the vector STL container.
SOURCE CODE:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Create a vector of integers
vector<int> numbers;
// Add elements to the vector
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
// Access elements using an index
cout << "The first element is: " << numbers[0] << endl;
// Iterate over the vector and print each element
cout << "The elements in the vector are: ";
for (const int& num : numbers) {
cout << num << " ";
}
cout << endl;
// Remove the last element
numbers.pop_back();
// Print the size of the vector
cout << "The size of the vector after pop_back is: " << numbers.size() << endl;
// Check if the vector is empty
if (numbers.empty()) {
cout << "The vector is empty." << endl;
} else {
cout << "The vector is not empty." << endl;
}
return 0;
}
OUTPUT:
The first element is: 1
The elements in the vector are: 1 2 3
The size of the vector after pop_back is: 2
The vector is not empty.
Explanation:
- Include the Header:
#include <vector>
is necessary to use thestd::vector
class. - Create a Vector:
std::vector<int> numbers;
creates a vector of integers. - Add Elements:
push_back
adds elements to the end of the vector. - Access Elements: You can use the subscript operator
[]
to access elements. - Iterate Over Elements: A range-based for loop is used to print all elements.
- Remove Elements:
pop_back
removes the last element. - Check Size:
size()
returns the number of elements in the vector. - Check if Empty:
empty()
returnstrue
if the vector has no elements.
No comments:
Post a Comment