Created
February 17, 2025 16:51
-
-
Save sjhalayka/e713754a6562b13ca3d712ebb235c530 to your computer and use it in GitHub Desktop.
c++ vectors to pointers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <memory> | |
using namespace std; | |
template<class T> | |
void test_function(T ***c, const size_t size_x, const size_t size_y, const size_t size_z) | |
{ | |
} | |
template<class T> | |
void test_function(T **c, const size_t size_x, const size_t size_y) | |
{ | |
} | |
template<class T> | |
void test_function(T *c, const size_t size_x) | |
{ | |
} | |
template<class T> | |
T*** get_pointer_from_vector(vector<vector<vector<T>>> &input_data, const size_t size_x, const size_t size_y) | |
{ | |
vector<vector<T*>> ptr_array2(size_x, vector<T*>(size_y)); | |
vector<T**> ptr_array1(size_x); | |
for (size_t i = 0; i < size_x; i++) | |
{ | |
for (size_t j = 0; j < size_y; j++) | |
ptr_array2[i][j] = input_data[i][j].data(); | |
ptr_array1[i] = ptr_array2[i].data(); | |
} | |
T*** legacy_ptr = ptr_array1.data(); | |
return legacy_ptr; | |
} | |
template<class T> | |
T** get_pointer_from_vector(vector<vector<T>>& input_data, const size_t size_x) | |
{ | |
vector<T*> row_ptrs(size_x); | |
for (size_t i = 0; i < size_x; i++) | |
row_ptrs[i] = input_data[i].data(); | |
T** legacy_ptr = row_ptrs.data(); | |
return legacy_ptr; | |
} | |
template<class T> | |
T* get_pointer_from_vector(vector<T>& input_data) | |
{ | |
T* legacy_ptr = input_data.data(); | |
return legacy_ptr; | |
} | |
int main(void) | |
{ | |
const size_t dim1 = 2, dim2 = 2, dim3 = 3; | |
vector<vector<vector<int>>> data3(dim1, vector<vector<int>>(dim2, vector<int>(dim3))); | |
test_function<int>(get_pointer_from_vector<int>(data3, dim1, dim2), dim1, dim2, dim3); | |
vector<vector<char>> data2(dim1, vector<char>(dim2)); | |
test_function<char>(get_pointer_from_vector<char>(data2, dim1), dim1, dim2); | |
vector<double> data1(dim1); | |
test_function<double>(get_pointer_from_vector<double>(data1), dim1); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment