How to Pass an Array to a Function

beginner c++17 containers

In C++ std::array are fixed in size, meaning you cannot change how many values the array holds after creating it. Arrays that can change their size are known as std::vector in C++. To pass a std::array to a function you need to know what its size will be. If you don’t know, or want to have arrays of different lengths, use std::vector.

With std::array

#include <array>
#include <unordered_set>
#include <iostream>

using std::unordered_set;
using std::array;

unordered_set<int> unique(const array<int, 12>& numbers) {
  unordered_set<int> uniqueNumbers;
  for (auto n : numbers) {
    uniqueNumbers.insert(n);
  }
  return uniqueNumbers;
}

int main() {
  array numbers{1, 2, 42, 8, 0, -7, 2, 5, 10, 3, -100, 5};
  auto uniqueNumbers = unique(numbers);

  std::cout << uniqueNumbers.size() << "\n";
}
10

With std::vector

#include <vector>
#include <unordered_set>
#include <iostream>

using std::unordered_set;
using std::vector;

unordered_set<int> unique(const vector<int>& numbers) {
  unordered_set<int> uniqueNumbers;
  for (auto n : numbers) {
    uniqueNumbers.insert(n);
  }
  return uniqueNumbers;
}

int main() {
  vector numbers{1, 2, 42, 8, 0, -7, 2, 5, 10, 3, -100, 5};
  auto uniqueNumbers = unique(numbers);

  std::cout << uniqueNumbers.size() << "\n";
}
10


For more C++ By Example, click here.