What is the best way to create a sparse array in C++?

后端 未结 11 2185
心在旅途
心在旅途 2020-11-29 01:45

I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation.

In short, I need to keep

11条回答
  •  没有蜡笔的小新
    2020-11-29 02:04

    For C++, a map works well. Several million objects won't be a problem. 10 million items took about 4.4 seconds and about 57 meg on my computer.

    My test application is as follows:

    #include 
    #include 
    #include 
    
    class triple {
    public:
        int x;
        int y;
        int z;
        bool operator<(const triple &other) const {
            if (x < other.x) return true;
            if (other.x < x) return false;
            if (y < other.y) return true;
            if (other.y < y) return false;
            return z < other.z;
        }
    };
    
    int main(int, char**)
    {
        std::map data;
        triple point;
        int i;
    
        for (i = 0; i < 10000000; ++i) {
            point.x = rand();
            point.y = rand();
            point.z = rand();
            //printf("%d %d %d %d\n", i, point.x, point.y, point.z);
            data[point] = i;
        }
        return 0;
    }
    

    Now to dynamically choose the number of variables, the easiest solution is to represent index as a string, and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index will look like "34,45,56". A simple implementation of this technique is as follows:

    std::map data data;
    char ix[100];
    
    sprintf(ix, "%d,%d", x, y); // 2 vars
    data[ix] = i;
    
    sprintf(ix, "%d,%d,%d", x, y, z); // 3 vars
    data[ix] = i;
    

提交回复
热议问题