मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 5 · पाठ 1 का 2पाठ्यक्रम में 11/18~12 min
मॉड्यूल पाठ (1/2)

सरणियाँ और वेक्टर

In C++, managing collections of data is primarily done through two tools: old-style arrays (C-style arrays) and vectors (std::vector). Understanding the difference between static and dynamic memory is fundamental to writing efficient code.


1. Static Arrays (C-style Arrays)

An array is a collection of elements of the same type stored in contiguous memory locations. The size of a static array must be known at compile time and cannot be changed later:

Code
int grades[5] = {18, 22, 25, 28, 30}; // Array of 5 integers

Key Characteristics:

  • Fixed Size: You cannot add or remove elements at runtime.
  • Stack Allocation: Very fast to allocate and deallocate.
  • Access: Done via the index operator [] (e.g., grades[0] for the first element).

2. Dynamic Vectors (std::vector)

The C++ Standard Template Library (STL) provides the std::vector class, which represents a dynamic array. To use it, you must include the <vector> header:

Code
#include <vector>

std::vector<int> numbers; // Creates an empty vector of integers

Common Operations:

  • Append to End: The .push_back(value) method inserts an element at the end of the vector, automatically reallocating memory if needed.
  • Size: The .size() method returns the number of elements currently in the vector.
  • Safe Access: In addition to the [] operator, you can use the .at(index) method (e.g., numbers.at(0)), which throws an exception if the index is out of bounds.
Code
std::vector<int> scores = {90, 85};
scores.push_back(95); // scores now contains {90, 85, 95}
std::cout << scores.size(); // Prints 3

Try it yourself

व्यायाम#cpp.m5.l1.e1
प्रयास: 0लोड हो रहा है...

Declare a std::vector of integers named numbers. Add the values 10, 20, and 30 inside it using the .push_back() method, then print its size using numbers.size().

संपादक लोड हो रहा है...
संकेत दिखाएँ

Declare the vector with `std::vector<int> numbers;`, insert the three numbers with `.push_back(value)`, and print it with `std::cout << numbers.size();`.

3 प्रयासों के बाद समाधान उपलब्ध है

व्यायाम#cpp.m5.l1.e2
प्रयास: 0लोड हो रहा है...

In main, a grades array of 5 elements is defined. Write a for loop to calculate the sum of all elements in the array, store it in the variable sum, and print it using std::cout.

संपादक लोड हो रहा है...
संकेत दिखाएँ

Use a `for (int i = 0; i < 5; ++i)`loop and sum each element inside the loop with`sum += grades[i];`.

3 प्रयासों के बाद समाधान उपलब्ध है

Quiz#cpp.m5.l1.q1
तैयार

What is the correct method to append an element to the end of a std::vector in C++?

Code
std::vector<int> numbers; // come aggiungere il valore 50?
उत्तर विकल्प