Skip to content

Instantly share code, notes, and snippets.

@muaddib1971
Last active July 30, 2024 02:32
Show Gist options
  • Save muaddib1971/bdbcd981f2138f180af31922e0b163c7 to your computer and use it in GitHub Desktop.
Save muaddib1971/bdbcd981f2138f180af31922e0b163c7 to your computer and use it in GitHub Desktop.
container examples for Operating Systems Principles
#include <random>
#include <iostream>
#define SIZE 10
int main() {
//a pointer to some integers - currently not allocated
int * array = nullptr;
//allocate space for 'size' integers
array = new int[SIZE];
int count;
//create the random number generator
std::mt19937 gen{};
//fill the array
for(count = 0; count < SIZE; ++count) {
array[count] = gen();
}
//print out the array
for(count = 0; count < SIZE; ++count) {
std::cout << array[count] << std::endl;
}
//free the array - note that we must use the square bracket form of 'delete'
//as we used the square bracket version of new.
delete[] array;
return EXIT_SUCCESS;
}
#include <random>
#include <iostream>
#include<array>
#define SIZE 10
int main() {
//declare an array based on the std::array template:
std::array<int, SIZE> array;
int count;
//create the random number generator
std::mt19937 gen{};
//fill the array
for(count = 0; count < SIZE; ++count) {
array[count] = gen();
}
//print out the array
for(count = 0; count < SIZE; ++count) {
std::cout << array[count] << std::endl;
}
//no need to free the memory as that is handled at program exit - at least
//for the array itself
return EXIT_SUCCESS;
}
#include <random>
#include <iostream>
#include <vector> // we need to include the vector library.
#define SIZE 10
int main() {
//We replace the pointer to the array with a vector:
std::vector<int> vec;
//allocate space for 'size' integers
int count;
//create the random number generator
std::mt19937 gen{};
//we can choose to just push_back elements and the vector will automatically
//allocate the space
for(count = 0; count < SIZE; ++count) {
vec.push_back(gen());
}
//print out the array
for(count = 0; count < SIZE; ++count) {
std::cout << vec[count] << std::endl;
}
//no need to free memory as the vector class is automatically freed.
return EXIT_SUCCESS;
}
#include <random>
#include <iostream>
#include <vector> // we need to include the vector library.
#define SIZE 10
int main() {
//We replace the pointer to the array with a vector:
std::vector<int> vec;
//allocate space for 'size' integers
int count;
//create the random number generator
std::mt19937 gen{};
//we reserve the space for the random numbers
vec.reserve(SIZE);
for(count = 0; count < SIZE; ++count) {
vec[count] = gen();
}
//print out the array
for(count = 0; count < SIZE; ++count) {
std::cout << vec[count] << std::endl;
}
//no need to free memory as the vector class is automatically freed.
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment