Converting 2d Array into Vector

I am trying to convert a 2d array into a vector. In the code below, the function "flatten" is supposed to take a 2 x 2 array and "flatten" it into a one-dimensional vector. But the code does not work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cassert>
#include <vector>

// The code uses features in c++11. Compile it using "g++ -std=c++11".

using namespace std;

vector<int> flatten(int a[2][2]);

int main()
{
    int a[2][2] {{0,1},{2,3}};
    flatten(a);
    vector<int> v{0,1,2,3};
    assert(flatten(a) == v);

    cout << "All tests have passed successfully." << endl;
}

vector<int> flatten(int a[2][2])
{
    vector<int> k;
    for(int i = 0; i < 4; ++i)
    {
        for (int r = 0; r <2; ++r)
        {
            for (int c = 0; c <2; ++c)
            {
                k.push_back(a[r][c]); 
            }
        }
    }
    return k;
}
Last edited on
closed account (E0p9LyTq)
Your for loop in flatten() is adding your array to the vector 4 times! No wonder it doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<int> flatten(int a[2][2])
{
   vector<int> k;

   for (int r = 0; r <2; ++r)
   {
      for (int c = 0; c <2; ++c)
      {
         k.push_back(a[r][c]);
      }
   }

   // add this to your function!
   std::cout << "The size of the vector is: " << k.size() << "\n";

   return k;
}


The size of the vector is: 4
The size of the vector is: 4
All tests have passed successfully.
Thank you! The following is a code that flattens a 100 x 200 2d array into a 1d vector. The code works. But is it clear to the coder what I am testing in the assert statements?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cassert>
#include <vector>

// The code uses features in c++11. Compile it using "g++ -std=c++11".

using namespace std;

vector<int> flatten(int a[100][200]);

int main()
{
    int a[100][200] {{0,1},{2,3}};
    vector<int> v {};
    
    flatten(a);
    v = flatten(a);
    
    assert(v[0]== 0);
    assert(v[1]== 1);
    assert(v[200]== 2);
    assert(v[201]==3);
    assert(v[202]==0);
    assert(v[2000]==0);
    
    cout << "All tests have passed successfully." << endl;
}
vector<int> flatten(int a[100][200])
{
    vector<int> k;
    
    for (int r = 0; r <100; ++r)
    {
        for (int c = 0; c <200; ++c)
        {
            k.push_back(a[r][c]); 
        }
    }
    return k;
}
Last edited on
Topic archived. No new replies allowed.