Monday, July 22, 2024

Program 11 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 11 Demonstrate the use of the vector STL container.

 

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:

  1. Include the Header: #include <vector> is necessary to use the std::vector class.
  2. Create a Vector: std::vector<int> numbers; creates a vector of integers.
  3. Add Elements: push_back adds elements to the end of the vector.
  4. Access Elements: You can use the subscript operator [] to access elements.
  5. Iterate Over Elements: A range-based for loop is used to print all elements.
  6. Remove Elements: pop_back removes the last element.
  7. Check Size: size() returns the number of elements in the vector.
  8. Check if Empty: empty() returns true if the vector has no elements.

No comments:

Post a Comment

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...