Three Methods of Passing Vectors to Functions in C++ and Their Applications

Nov 22, 2025 · Programming · 9 views · 7.8

Keywords: C++ | vector passing | function parameters | binary search | performance optimization

Abstract: This article comprehensively examines three primary methods for passing vectors to functions in C++ programming: pass by value, pass by reference, and pass by pointer. Through analysis of a binary search algorithm implementation case study, it explains the syntax characteristics, performance differences, and applicable scenarios for each method. The article provides complete code examples and error correction guidance to help developers understand proper vector parameter passing and avoid common programming mistakes.

Introduction

In C++ programming, vectors as essential components of the Standard Template Library (STL) frequently need to be passed between different functions. Proper vector parameter passing is crucial for program performance and functionality implementation. Based on actual programming problems, this article systematically analyzes three main methods for passing vectors to functions.

Basic Methods of Vector Passing

Passing Vectors by Reference

Pass by reference is one of the most commonly used methods, directly operating on the original vector without creating a copy. Use the & symbol in function declaration to indicate reference passing:

int binarySearch(int first, int last, int search4, vector<int>& random);

When calling the function, simply pass the vector name:

vector<int> random(100);
found = binarySearch(first, last, search4, random);

Inside the function, you can directly use the dot operator to access vector members, such as random[mid]. This method is efficient, and all modifications will be reflected in the original vector.

Passing Vectors by Pointer

Pass by pointer operates on vectors through memory addresses, using the * symbol in function declaration:

int binarySearch(int first, int last, int search4, vector<int>* random);

Function calls require obtaining the vector address:

found = binarySearch(first, last, search4, &random);

Inside the function, you must use the arrow operator or dereference operation:

// Using arrow operator
if (search4 > random->at(mid))
    first = mid + 1;
// Or using dereference
if (search4 > (*random)[mid])
    first = mid + 1;

Passing Vectors by Value

Pass by value creates a complete copy of the vector, and modifications inside the function won't affect the original vector:

int binarySearch(int first, int last, int search4, vector<int> random);

This method is suitable for scenarios where the original vector doesn't need modification, but performance is poor for large vectors due to the copying overhead.

Binary Search Algorithm Case Study

Algorithm Implementation

The following is a complete binary search function implementation demonstrating proper vector passing:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int binarySearch(int first, int last, int search4, vector<int>& random) {
    while (first <= last) {
        int mid = first + (last - first) / 2;
        if (random[mid] == search4)
            return mid;
        else if (random[mid] < search4)
            first = mid + 1;
        else
            last = mid - 1;
    }
    return -1;
}

int main() {
    vector<int> random(100);
    // Fill with sorted random values
    srand(time(0));
    for (int i = 0; i < 100; i++) {
        random[i] = rand() % 201;
    }
    sort(random.begin(), random.end());
    
    int search4 = 50; // Value to search for
    int first = 0;
    int last = random.size() - 1;
    
    int found = binarySearch(first, last, search4, random);
    
    if (found != -1)
        cout << "Element found at index: " << found << endl;
    else
        cout << "Element not found" << endl;
    
    return 0;
}

Common Error Corrections

The original code contained several critical errors:

  1. Parameter type mismatch: Function declaration used pointer type, but vector object was passed during call
  2. Missing pointer dereference: Used random[mid] directly instead of (*random)[mid] inside function
  3. Boundary value errors: first and last should be set as index values rather than vector element values
  4. Uninitialized variables: search4 variable used before assignment

Performance Comparison and Selection Recommendations

Memory Usage

Pass by value requires additional memory to store vector copies, while pass by reference and pass by pointer directly operate on original data without extra memory.

Execution Efficiency

Pass by value performs significantly worse for large vectors due to data copying. Pass by reference and pass by pointer have similar performance characteristics.

Code Safety

Pass by reference is generally safer than pass by pointer, avoiding null pointer and memory management issues. For vectors that shouldn't be modified, use constant references:

int binarySearch(int first, int last, int search4, const vector<int>& random);

Recommended Usage Scenarios

Conclusion

Proper vector parameter passing is an essential skill in C++ programming. Pass by reference is the optimal choice in most situations, and combining it with constant references can further enhance code safety and efficiency. By understanding the characteristics and applicable scenarios of different passing methods, developers can write more efficient and reliable C++ programs.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.