How to Initialize a Vector with Values between a Range in C++?
Last Updated :
27 Feb, 2024
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++
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
srand ( time (0));
int start = 1, end = 5;
vector< int > myVector;
for ( int i = start; i <= end; i++) {
int randNum = start + rand () % (end - start + 1);
myVector.push_back(randNum);
}
cout << "Vector: " ;
for ( int i : myVector) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Time Complexity: O(N) where N is the number of elements.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...