Introduction
In the previous lesson, we explored the differences between arrays and vectors in C++. Now, let’s dive deeper into how to pass arrays and vectors to functions in C++. Passing these data structures to functions is a common task in C++ programming, and understanding the syntax and usage is crucial for writing efficient and modular code.
In this lesson, we’ll cover:
- The syntax for passing arrays and vectors to functions.
- Example problems and solutions.
🔹 Passing Arrays to Functions
Syntax for Passing Arrays
When passing an array to a function, you pass a pointer to the first element of the array. The size of the array is often passed as a separate argument.
void functionName(T arr[], int size);
- T is the data type of the array.
- arr[] is the array passed to the function.
- size is the number of elements in the array.
Example 1: Finding the Maximum Element in an Array
Problem Statement
Write a program that takes an array of integers as input, passes it to a function, and finds the maximum element in the array.
Solution
#include <iostream>
using namespace std;
// Function to find the maximum element in an array
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
// Pass the array to the function
int maxElement = findMax(arr, size);
cout << "The maximum element in the array is: " << maxElement << endl;
return 0;
}
Output
The maximum element in the array is: 50
🔹 Passing Vectors to Functions
Syntax for Passing Vectors
Vectors are passed to functions by reference or by value. Passing by reference is more efficient for large vectors.
void functionName(vector<T> &vec);
- T is the data type of the vector.
- &vec is the vector passed by reference, meaning that any modifications in the function will directly affect the original vector.
- Note:
For a deeper understanding of how references work (indicated by &), please refer to the additional example at the end of this tutorial.
Example 2: Calculating the Sum of Elements in a Vector
Problem Statement
Write a program that takes a vector of integers as input, passes it to a function, and calculates the sum of its elements.
Solution
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the sum of elements in a vector
int calculateSum(vector<int> &vec) {
int sum = 0;
for (int i = 0; i < vec.size(); i++) {
sum += vec[i];
}
return sum;
}
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
// Pass the vector to the function
int sum = calculateSum(vec);
cout << "The sum of elements in the vector is: " << sum << endl;
return 0;
}
Output
The sum of elements in the vector is: 15
Note about size():
- The size() function is a member of the vector class, and it returns the number of elements in the vector.
- Important: Since vectors are dynamic, they don’t require manual size calculations like arrays. You can simply use vec.size() to get the number of elements.
🔹 Comparing Array and Vector Usage
Example 3: Modifying Elements in an Array and Vector
Problem Statement
Write a program that demonstrates how to modify elements in an array and a vector by passing them to functions.
Solution
#include <iostream>
#include <vector>
using namespace std;
// Function to modify an array
void modifyArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2; // Double each element
}
}
// Function to modify a vector
void modifyVector(vector<int> &vec) {
for (int i = 0; i < vec.size(); i++) {
vec[i] *= 2; // Double each element
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
vector<int> vec = {1, 2, 3, 4, 5};
// Pass the array and vector to functions
modifyArray(arr, size);
modifyVector(vec);
cout << "Modified array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "Modified vector: ";
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
Output
Modified array: 2 4 6 8 10
Modified vector: 2 4 6 8 10
_________________________________________________________________
Additional Note on & (Reference) in Vectors and Arrays
In C++, when we pass a vector or array to a function using &, we are passing it by reference. This means that the function works directly with the original vector or array, not a copy. Any changes made to the vector or array inside the function will directly affect the original vector or array outside the function. This is more efficient for large vectors because it avoids the overhead of copying the entire data structure.
- Example of Passing by Reference:
void modifyVector(vector<int> &vec)
The & symbol indicates that the vector is being passed by reference. This allows the function to directly modify the contents of the vector.
Understanding References with & (simple example for beginners)
To understand the concept of passing by reference using &, consider this simple example:
#include <iostream>
using namespace std;
void modifyValue(int &x) { // Passed by reference
x = 20; // Modify the original value
}
int main() {
int num = 10;
modifyValue(num); // Pass 'num' by reference
cout << "Modified value: " << num << endl; // Output will be 20
return 0;
}
Output:
Modified value: 20
Explanation:
- In this example, modifyValue takes an integer parameter x passed by reference. This means that when x is modified inside the function, the original num variable is also modified.
- So, the value of num changes to 20 inside the function, and the modified value is reflected when we print it in main().
Example 2: Passing by Value (without &)
#include <iostream>
using namespace std;
void modifyValue(int x) { // Passed by value
x = 20; // Modify the local copy of the value
}
int main() {
int num = 10;
modifyValue(num); // Pass 'num' by value
cout << "Modified value: " << num << endl; // Output will be 10
return 0;
}
Output:
Modified value: 10
Explanation:
- In this case, modifyValue takes an integer parameter x passed by value. This means that a copy of num is passed to the function, and any changes made to x inside the function do not affect the original num in main().
- So, even though we modify x inside the function, the value of num remains unchanged and is still 10 when printed.
Summary:
- Passing by Reference (&) allows the function to modify the original variable, so changes are reflected outside the function.
- Passing by Value creates a copy of the variable, so modifications inside the function do not affect the original variable.
_________________________________________________________________
'C++ Beginner' 카테고리의 다른 글
cpp_016: Comparing C-Style Arrays, std::array, and std::vector in C++ (0) | 2025.04.05 |
---|---|
cpp_015: STL Array in C++ (0) | 2025.03.10 |
cpp_014: Exploring Different Types of For Loops in C++ — Range-Based and Reference-Based Loops (0) | 2025.03.01 |
cpp_013: Arrays vs. Vectors in C++ - Understanding the Differences with Examples (0) | 2025.02.26 |
cpp_012: Introduction to Vectors in C++ (0) | 2025.02.17 |