简体   繁体   English

从2D阵列获取一维数组索引

[英]Get 1D array index from a 2D array

Is there a way to get the array index of a 1D array from a 2D array? 有没有办法从2D数组中获取一维数组的数组索引?

For Eg: I have a 2D array, the array size is unknown and changes (I've used std::vector) to push_back as and when required. 对于Eg:我有一个2D数组,数组大小未知,并且在需要时更改(我已经使用std :: vector)到push_back。 This works fine as long as its a 2D array but I need to get the 1D array index of this 2D array. 只要它是一个2D数组,这个工作正常,但我需要获得这个2D数组的1D数组索引。

2D array:
Group 1 - 1, 2, 3
Group 2 - 4, 5, 6
Group 3 - 7, 8, 9, 10, 11, 12

and so on. 等等。

So, basically is there a quick way to know that when 6 is selected from Group 2 ie Array[1][2] = 6 => I need the array index as: 1D array=> Array[5] = 6 => ie I need 5 as my answer. 所以,基本上有一种快速的方法可以知道当从组2中选择6时,即Array [1] [2] = 6 =>我需要数组索引为:1D array => Array [5] = 6 => ie我需要5作为我的答案。 I have tried several things but no luck so far. 到目前为止,我尝试了几件但没有运气。 Any suggestions? 有什么建议么?

If your data is static, you can make another array in which you will store the offset for each 1D array. 如果您的数据是静态的,则可以创建另一个数组,在该数组中存储每个1D数组的偏移量。 For your example, you will have the following array offset = {0, 3, 6} . 对于您的示例,您将具有以下数组offset = {0, 3, 6} Then you can find the index by offset[row] + col . 然后你可以通过offset[row] + col找到索引。

If you can change the row sizes, then you can store the size of each row in a Binary indexed tree and find the offset in O(log n) with a single query, where n is the amount of rows (1D vectors). 如果您可以更改行大小,则可以将每行的大小存储在二进制索引树中,并使用单个查询在O(log n)中查找偏移量,其中n是行数(1D向量)。 However, each time you change the row size, you would have to update the structure again in O(log n). 但是,每次更改行大小时,都必须在O(log n)中再次更新结构。

If you are creating a vector of vectors (or a list of vectors), the memory locations are not guaranteed to be related. 如果要创建向量向量(或向量列表),则不保证内存位置相关。 So to make it behave like a 1-dimensional array, you would need to wrap the container in your own class and overload operator[] . 因此,为了使其行为像一维数组,您需要将容器包装在您自己的类中并重载operator[] That operator would then need to check the index to determine the proper vector element to return. 然后,该运算符需要检查索引以确定要返回的正确向量元素。 A simplified version might look like: 简化版可能如下所示:

T& operator[](std::size_t index)
{
    std::size_t temp = index;
    if (index < myVectors[0].size())
    {
        return myVectors[0][index];
    }

    temp = index - myVectors[0].size()
    if (temp < myVectors[1].size())
    {
        return myVectors[1][temp];
    }

    // etc ...
}

You can simplify it to a loop: 您可以将其简化为循环:

T& operator[](std::size_t index)
{
    std::size_t temp = index;
    for (std::size_t i = 0; i < myVectors.size(); ++i)
    {
        if (temp < myVectors[i].size())
        {
            return myVectors[i][temp];
        }
        temp -= myVectors[i].size();
    }
    throw std::out_of_range("Array access out of bounds!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM