How do I generate random numbers on the heap?

I have no idea how to add "new" to dynamically allocate each point. I want to randomly generate 10 points between -10 and 10 on the heap. The code works, but the points are not generated on the heap. I tried using a vector too, but I do not think you can use "new" with vectors? Is that because a vector already dynamically allocates?

1
2
3
4
5
6
7
default_random_engine engine{ static_cast<unsigned int>(time(0)) };
uniform_int_distribution<int> randomInt{ -10, 10 };
for (int i{ 1 }; i <= 10; ++i)
{
cout << (randomInt(engine)) << endl;
}
return 0;
Last edited on
std::vector stores its elements on the heap. No need to use new.

1
2
3
4
5
std::vector<int> points(10);
for (int& point : points)
{
	point = randomInt(engine);
}
Last edited on
Do you have to use the "std::" part or can it just be vector<int> points(10)?
If you have using namespace std; (or using std::vector<int>) earlier in the code you don't need to write std::. I just did it out of habit.
I updated it. Am I still on the heap? And did I free it at the end?

1
2
3
4
5
6
7
8
9
        vector<int> myVector(10);
	default_random_engine engine{ static_cast<unsigned int>(time(0)) };
	uniform_int_distribution<int> randomInt{ -10, 10 };
	for (int i{ 0 }; i < 10; ++i)
	{
		myVector[i] = randomInt(engine);
		cout << myVector[i] << endl;
	}
	myVector.clear();
Last edited on
Am I still on the heap?

Yes, the numbers are stored on the heap.

did I free it at the end?

If the vector goes out of scope you don't need to do anything to free the elements because the vector will do that automatically in its destructor.
Last edited on
Just out of interest, why are you so keen for them to be on the heap?
Thanks, Peter.

Oh, I am doing an assignment. Involves classes, functions, and pointers. I only posted one part of it, which involves the program generating random coordinates. These coordinates have to be on the heap. But my program cannot have any memory leaks. That is why I was asked if I freed the memory. I was not sure.
Last edited on
Hi petey, what Peter87 showed you is great C++, however, since this is a school assignment, it's possible that your instructor wanted you to use "raw" dynamic arrays instead of C++ vectors.

The code you have now does indeed meet the stated requirements, but you might want to make sure with your professor that you can use std::vector. Some professors can be stubborn...
your professor may not want you to be doing this using tools that handle it for you, but may want you to get your hands dirty.

if that is the case you may need to generate actual pointers and allocate and deallocate the memory yourself.

that looks like this

int *ip = new int[some_size]; //allocate memory, on heap
...
for(...)
ip[x++] = randomvalue;
...
done with it
delete[] ip; //release memory, no leak

It is better not do do things this way:
-its a pain to resize the memory block if you needed more than some_size
- it is easy to make mistakes and cause problems including memory leaks, memory access, and other problems
- its more code and clutter
there are other issues with it as well. But you should know how to do this (in case you need to edit C code, which is often mixed in c++ programs) and how to read it (older c++ code uses this a lot) or if you just need to do it (rare, but possible).

the language also wraps this in a smart pointer that helps rather than doing it by hand as I have shown. You can also handle some of this using classes and destructors to avoid leaks, but generally, its just best overall to let the tools handle as much of this as possible.

Thanks for the replies. This is an update. The assignment says I can use unique pointers or shared pointers. I am guessing that I should, since I have to make three different functions that removes the last point from the graph, add a point to the graph using a pointer, and removes all pointers in a field and clears the memory for each object removed.
I was just testing things out with the random number generator to see how I could get it to work.

1
2
3
4
5
6
7
8
9
10
11
        const int SIZE = 11;
	int *myPointer = new int[SIZE];
	default_random_engine engine{ static_cast<unsigned int>(time(0)) };
	uniform_int_distribution<int> randomInt{ -11, 11 };
	for (size_t i = 0; i < SIZE; i++)
	{
		myPointer[i] = randomInt(engine);
		cout << myPointer[i] << endl << endl;
	}
        delete[] myPointer;
        return 0;


This is the rest of my program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Graph
{
private:
	vector<const Point*> m_vecPoints; 

public:
	Graph()
	{

	}
	void addPoint(const Point*) 
	{

	}
	void clearGraph()
	{

	}
	void plot()
	{

	}
	bool removePoint(const int x, const int y) 
	{

	}
};

class Point
{
private:
	int m_x;
	int m_y;

public:
	Point(int x, int y)
	{
		m_x = x;
		m_y = y;
	}
	void setX(int x)
	{
		m_x = x;
	}
	void setY(int y)
	{
		m_y = y;
	}
	int getX()
	{
		return m_x;
	}
	int getY()
	{
		return m_y;
	}
	double distanceFromOrigin()
	{
		return sqrt(pow(m_x, 2) + pow(m_y, 2));
	}
};

int main()
{
	const int SIZE = 11;
	int *myPointer = new int[SIZE];
	default_random_engine engine{ static_cast<unsigned int>(time(0)) };
	uniform_int_distribution<int> randomInt{ -11, 11 };
	for (size_t i = 0; i < SIZE; i++)
	{
		myPointer[i] = randomInt(engine);
		cout << myPointer[i] << endl << endl;
	}

	delete[] myPointer; 
	return 0;
}


addPoint adds a point to the Graph by adding the passed in pointer to a Point object to the m_vecPoints.

clearGraph removes all the pointers in the m_vecPoints and frees the memory for each object removed.

Graph is the default constructor.

plot should display each point on the graph in order based on the distance from the origin (closest to furthest).

removePoint should remove the point from the graph if it exists and returns true if the point was removed and false if the point wasn’t removed.

The driver code should:
1) Randomly generate 11 points (x and y values should be between -11 and +11) and each point to the Graph. Each point must be dynamically allocated.
2) Plot the Graph
3) Remove the last point added from the Graph.
4) Attempt to remove a point that doesn’t exist in the Graph, the point must be a valid point (x and y values between -11 and +11)
5) Clear the Graph
6) Repeat steps 1 and 2.

The thing that threw me off was the vector<const Point*> m_vecPoints in private, and using pointers. I was not sure if I should use a vector.
Last edited on
Topic archived. No new replies allowed.