Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C++ equivalent of a 3 dimensional array

Status
Not open for further replies.

nappaji

Programmer
Mar 21, 2001
76
US
How do you declare a 3-dimensional array in C++?

For ex:
int abc[100][20][5];

Can it be done through vectors?? or what built in type can I use??

Also, if I have to do dynamic memory allocation, i.e. not hardcoding the array sizes, how do I do it in C++??
 
Here's an example. The typdefs aren't necessary but with a 3-D vector it makes things easier.
Code:
#include <iostream>
#include <vector>

typedef std::vector<int> D1IntVec;
typedef std::vector<D1IntVec> D2IntVec;
typedef std::vector<D2IntVec> D3IntVec;

int main()
{
    int xDim = 0;
    int yDim = 0;
    int zDim = 0;
    while (xDim == 0 || yDim == 0 || zDim == 0)
    {
        std::cout << "Input the non-zero dimensions";
        std::cout << "separated by spaces (e.g. 10 20 30):" << std::endl;
        std::cin >> xDim >> yDim >> zDim;
    }

    D3IntVec d3Array(xDim, D2IntVec(yDim, D1IntVec(zDim)));

    std::cout << "\nDimensions of array are: ";
    std::cout << d3Array.size() << "x";
    std::cout << d3Array[0].size() << "x";
    std::cout << d3Array[0][0].size() << std::endl;
    std::cout << "Default value is: " << d3Array[0][0][0] << std::endl;
}
 
It seems STL <valarray> is the best choice for numeric data dynamic array base. It's more efficient and has group ops etc...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top