简体   繁体   English

将2D阵列压缩为1D阵列

[英]Compress a 2D array into a 1D Array

i have a quad (2D array) which is composed of numbers which ranges from 0 to 255 and the most frequent value of the array ( in my case 2) is the background value 我有一个四边形(2D数组),该数组由范围从0到255的数字组成,并且该数组的最频繁值(在我的情况下为2)是背景值

i have to put all the values of the array except the background value ( i have to ignore all cases that contains a 2) in a 1D array with this arrangement 我必须将除背景值以外的所有数组值(我必须忽略所有包含2的情况)以这种排列方式放置在1D数组中

the line,the column,the value,the line,the next column,the next value 行,列,值,行,下一列,下一个值

for example i have 例如我有

{2,3,2,2},
{2,2,2,2},

in the 1D array it will be like { 1,2,3,} 在一维数组中,它将像{ 1,2,3,}

i added spaces to make it more readable 我添加了空格以使其更具可读性

here is my array 这是我的数组

int image1[MAXL][MAXC]=
{
    {2,3,2,2},
    {2,2,2,2},
    {2,255,2,2},
    {255,2,2,2},
    {2,255,2,2}
};

and the loop 和循环

 for (int i = 0; i<nbc;i++)
{
    for (int j=0; j<nbl;j++)
    {
        if (image1[j][i]==BackColor)
        {

        }
        else 
    }
}

nbc and nbl are respectively the number of columns and lines nbc和nbl分别是列数和行数

thanks you for your help 谢谢你的帮助

EDIT : i completely failed my example i didn't ignored the 2, should be fine now 编辑:我完全失败了我的示例,我没有忽略2,现在应该可以了

A simple approach using std::vector 使用std::vector简单方法

std::vector<int> result;
for (int i = 0; i<MAXL;i++)
{
    for (int j=0; j<MAXC;j++)
    {
        if (image1[i][j] != BackColor)  // Notice !=
        {
            result.push_back(i+1);
            result.push_back(j+1);
            result.push_back(image1[i][j]);
        }
    }
}


for (auto x : result)
{
    std::cout << x << " ";
}
std::cout << endl;

Output: 输出:

1 2 3 3 2 255 4 1 255 5 2 255 1 2 3 3 2 255 4 1 255 5 2 255

http://ideone.com/yJawu5 http://ideone.com/yJawu5

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

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