class memory allocation

How do I allocate memory for an array of 'n' classes, and how do I access them (just a simple code).
Thanks!
Use std::vector.

It would be like
1
2
std::vector<int> blah(10); // 10 ints
blah[3] = 6; // Just like a regular array -- sets the 4th element to 6 

(that's just an extraordinarily simple example -- see http://www.cplusplus.com/reference/stl/vector/ )
Last edited on
did you mean How do you allocate memory for n objects from class?
maybe somthing like this ?
1
2
3
4
5
6
class sample {public:int x;};
int main (){
sample array[10];
array[5].x=999;
array[4].x=1;
return 0;}
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
#include <iostream>
#include <vector>
#include <limits>
using namespace std;

struct Example
{
   void Access()
   {
      cout << "Accessing a class" << endl;
   }
};

int main()
{
   int n = 0;

   cout << "Enter n: ";
   cin >> n;
   cin.sync();

   //allocating memory for an array of 'n' Examples
   vector<Example> nExamples(n);

   //accessing each of them
   for(vector<Example>::iterator iter = nExamples.begin(); iter != nExamples.end(); ++iter)
   {
      iter->Access();
   }

   //or just one of them
   nExamples[n - 1].Access();

   cout << "Press ENTER to continue..." << std::endl;
   cin.ignore( numeric_limits<streamsize>::max(), '\n' );

   return 0;
}


EDIT: ninja'd
Last edited on
Topic archived. No new replies allowed.