C++ Online Compiler
Example: FindLargestDynamicVector in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// FindLargestDynamicVector #include <iostream> #include <vector> // Required for std::vector #include <limits> // Required for std::numeric_limits int main() { int size; // Step 1: Get array size from user std::cout << "Enter the number of elements: "; std::cin >> size; // Step 2: Validate size if (size <= 0) { std::cout << "Array size must be positive." << std::endl; return 1; } // Step 3: Declare a std::vector of integers with the specified size // The vector handles dynamic memory allocation internally std::vector<int> numbers(size); // Step 4: Get elements from the user std::cout << "Enter " << size << " elements:" << std::endl; for (int i = 0; i < size; ++i) { std::cout << "Element " << i + 1 << ": "; std::cin >> numbers[i]; } // Step 5: Find the largest element // Initialize largest with the smallest possible integer value // This handles cases where all elements are negative int largest = std::numeric_limits<int>::min(); if (size > 0) { // Ensure vector is not empty before accessing largest = numbers[0]; // If vector is not empty, can initialize with first element } for (int i = 1; i < size; ++i) { // Start from the second element if (numbers[i] > largest) { largest = numbers[i]; } } // Step 6: Display the largest element std::cout << "The largest element is: " << largest << std::endl; return 0; // std::vector automatically deallocates memory when it goes out of scope }
Output
Clear
ADVERTISEMENTS