In C++, vectors are dynamic containers that can resize automatically when elements are inserted or deleted during the runtime. In this article, we will learn how to initialize a vector with a range of values in C++.
Example:
Input: start = 1, end =5 Output: myVector: {1, 5, 3, 4}
Initialize a Vector with Values between a Range in C++
We can initialize a vector with a range of values by using a loop and a random number generator srand() with modular arithmetic such that the number generated would be in between the upper and lower bound.
Approach
- Create a random number generator object and use the current time as a seed for a random generator.
- Define the start and end of the range for the random numbers.
- Use a for loop with n iterations to generate random numbers within the given range and insert them into the vector. To make the number in the desired range, use the formula: start + rand() % (end - start + 1).
C++ Program to Initialize a Vector with Values between a Range
// C++ Program to show how to Initialize a Vector with
// Values between a Range
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Use current time as seed for random generator
srand(time(0));
// Start and end of range
int start = 1, end = 5;
// Vector declaration
vector<int> myVector;
// Initializing the vector with a range of random values
for (int i = start; i <= end; i++) {
int randNum = start + rand() % (end - start + 1);
myVector.push_back(randNum);
}
// Printing the vector
cout << "Vector: ";
for (int i : myVector) {
cout << i << " ";
}
cout << endl;
return 0;
}
Output
Vector: 2 5 1 4 3
Time Complexity: O(N) where N is the number of elements.
Auxiliary Space: O(N)