To get a sub-array in C++, you can use array slicing or vector slicing.
In this example,
numbers
with some values.#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
vector<int> subArray(numbers.begin() + 2, numbers.begin() + 5);
cout << "Sub-array: [";
for (int i : subArray) {
cout << i << ", ";
}
cout << "]" << endl;
return 0;
}
Sub-array: [3, 4, 5, ]
In this example,
colors
with some values.#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> colors = {"red", "green", "blue", "yellow", "orange"};
vector<string> subArray(colors.begin() + 1, colors.begin() + 4);
cout << "Sub-array: [";
for (string color : subArray) {
cout << color << ", ";
}
cout << "]" << endl;
return 0;
}
Sub-array: [green, blue, yellow, ]
In this tutorial, we learned How to get Sub Array in C++ language with well detailed examples.