Array Newb Question

Have an issue with an array within a class that should be populated with values via function calls. Now the array is started within the class as

std::string* ArrayName;

This class is also defined as a vector, which I understand to be an array.

Within the function, I have tried a couple methods of assigning the array values. The typical array assigning tutorials involve arrays that are started via the vector or [arraysize]; which is easily understood, however for this assignment I'm not allowed to change these conditions. I had it working using the arrays I'm use to. If someone could just point me to a tutorial of this type of array calls, I'd probably be ok.


Class Test{

std::string* ArrayName;

}

Outside .h file, vector<Test> test

I'm not exactly sure what you are needing help with. Though if you can use vectors I would probably use std::vector<std::string> ArrayName; that way you will not have to manage the memory allocation manually.

If you are asking how to populate the array then you probably would want something like this:

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 <string>

class Test
{
    //by default they are private but if you wish you can put private: before
    int *array; //for this example I'll use int to make it simple
    std::size_t arraySize;

    public:
        //in your program you should use separate files I have them inlined to make things simplier
        ~Test(void)
        {
            delete [] array; //delete [] is called since I allocated with new []
            //You will use delete if new is called
        }

        void populateArray(std::size_t size)
        {
            arraySize = size;
            array = new int[size]; //allocate memory
            for(std::size_t i = 0; i < size; ++i) array[i] = i;
        }

        void outputArray(void)
        {
            for(std::size_t i = 0; i < arraySize; ++i) std::cout << array[i] << std::endl;
        }
};

int main()
{
    Test t;
    t.populateArray(10);
    t.outputArray();

    return 0;
} //t is destroyed
0
1
2
3
4
5
6
7
8
9


*typo
Last edited on
Thanks for the assistance, I managed to figure it out. ^^
Topic archived. No new replies allowed.