简体   繁体   中英

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

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

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,}

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

thanks you for your help

EDIT : i completely failed my example i didn't ignored the 2, should be fine now

A simple approach using 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

http://ideone.com/yJawu5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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