Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to convert a 2D vector to a 1D vector in C++

2 Answers

0 votes
#include <iostream>
#include <vector>

std::vector<int> arr2DTo1D(const std::vector<std::vector<int>>& arr2d) {
    std::vector<int> arr(arr2d.size() * arr2d[0].size());
    int k = 0;
    
    for (size_t i = 0; i < arr2d.size(); i++) {
        for (size_t j = 0; j < arr2d[i].size(); j++) {
            arr[k++] = arr2d[i][j];
        }
    }
    
    return arr;
}

int main() {
    std::vector<std::vector<int>> arr2d = { 
            { 5, 6, 1 }, 
            { 3, 8, 0 },
            { 9, 2, 7 } 
    };

    std::vector<int> arr = arr2DTo1D(arr2d);

    for (int n : arr) {
        std::cout << n << "\t";
    }
}


 
/*
run:
 
5	6	1	3	8	0	9	2	7
 
*/

 



answered Aug 14, 2024 by avibootz
0 votes
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<std::vector<int>> arr2d = { 
            { 5, 6, 1 }, 
            { 3, 8, 0 },
            { 9, 2, 7 } 
    };
 
    std::vector<int> arr;

    for (const auto& row : arr2d) {
        arr.insert(arr.end(), row.begin(), row.end());
    }
 
    for (int n : arr) {
        std::cout << n << "\t";
    }
}
 
 
  
/*
run:
  
5	6	1	3	8	0	9	2	7
  
*/

 



answered Aug 15, 2024 by avibootz

Related questions

3 answers 106 views
1 answer 91 views
1 answer 123 views
1 answer 129 views
1 answer 136 views
2 answers 112 views
112 views asked Aug 14, 2024 by avibootz
1 answer 135 views
...