so i'm running my head against a wall at the Moment. I want to create a dynamic array, which can contain numbers or text - but most likely numbers.
At the Moment i'm using:
string test[];
for that purpose.
Okay, now the thing is. I want to dynamically fill the array, if the Element is not already in the array. I've tryed googling solution, but most of them came up with vector, which wouldn't work in this case, because the array can be any size.
Again:
Check if the Element is in the Array, that can be empty or not
If Element is not in the Array, put it in.
Anybody got a Solution for this, please? Would be very thankfully!
Thank you very much for all those comments and answers. I just noticed one major difference from between what i found in the net and what you guys posted. if i use test[] it won't work, but if i use test{} everything is fine. Can somebody maybe explain me why is that?
So if I understood correctly you're trying to get an dynamic array which changes its size depending on how much elements are in there? Well then use vector. It does excatly this! And its pretty fast and the C++ standard for tasks like that.
Using a vectoralso allows you to use std::find. So to fullfill your task do something like that:
std::vector<std::string> test{"Hello"};
if (std::find(test.begin(), test.end(), "World!") == test.end())
test.push_back("World!");
Or even better, use std::set wich only allows unique elements:
std::set<std::string> test{"Hello"};
test.insert("World"); // works
test.insert("Hello"); // won't work
If you realy want to use an array then I would recommend you to write a template class to manage the array and then allocate the array on the heap.
template<typename T>
class Array
{
private:
T *data;
unsigned int size;
unsigned int index;
public:
Array()
{
size = 100;
index = 0;
data = new T[size];
}
~Array()
{
delete[] data;
}
void push_back(const T& val)
{
if (index == size)
{ // reallocate data if there is no memory left to store val
std::vector<T> tmp(data, data + size);
delete[] data;
size += 100;
data = new T[size];
for (size_t i = 0; i < tmp.size(); i++)
data[i] = tmp[i];
data[index++] = val;
}
else
{
data[index++] = val;
}
}
T& operator[](const unsigned int& i)
{
if (i >= size)
throw std::runtime_error("i out of bounds");
return data[i];
}
};
You then need to search in the array for an existing value, and if you couldn't find it use push_back to push the value into the array. Or use the subscript operator [] like you're used to.
Related
Background: this is a followup to #pari's answer to Constant-sized vector.
My type, metadata_t does not have a default constructor.
I use std::make_unique for fixed-size arrays that the size is not available in compile-time. (ie const size).
typedef std::unique_ptr<metadata_t[]> fixedsize_metadata_t;
fixedsize_metadata_t consolidate(const std::vector<metadata_t> &array) {
// note: this is run-time:
auto n = array.size();
return fixedsize_side_metadata_t(array.begin(), array.end()); // error
return fixedsize_side_metadata_t(array); // error
return std::unique_ptr<metadata_t[]>(0); // no error, but not useful
return std::unique_ptr<metadata_t[]>(n); // error
}
However, the constructor of unique_ptr<...[]> only accepts a size (integer). How do I initialise and copy my vector into my unique_ptr<[]>?
I tried std::unique_ptr<metadata_t[]>(array.size()); to prepare and then copy/populate the contents in the next step, but it shows a compile error.
Note: I use C++20 (or higher if it was available). Could make_unique_for_overwrite be useful? ( C++23 ).
Note: At first I thought generate (as in this answer) can do it, but it does not solve my problem because n is a run-time information.
The size of my vector is determined at run-time.
The whole point of this function is to convert my std::vector into a fixed-size data structure (with run-time size).
The data structure does not have to be unique_ptr<T[]>.
The old title referred to unique_ptr but I am really looking for a solution for a fixed-size data structure. So far, it is the only data structure I found as a "constant-size indexed container with size defined at runtime".
You can't initialize the elements of a unique_ptr<T[]> array with the elements of a vector<T> array when constructing the new array (UPDATE: apparently you can, but it is still not going to be a solution solved with a single statement, as you are trying to do).
You will have to allocate the T[] array first, and then copy the vector's elements into that array one at a time, eg:
typedef std::unique_ptr<metadata_t[]> fixedsize_metadata_t;
fixedsize_metadata_t consolidate(const std::vector<metadata_t> &array) {
fixedsize_metadata_t result = std::make_unique<metadata_t[]>(array.size());
std::copy(array.begin(), array.end(), result.get());
return result;
}
UPDATE: you updated your question to say that metadata_t does not have a default constructor. Well, that greatly complicates your situation.
The only way to create an array of objects that don't support default construction is to allocate an array of raw bytes of sufficient size and then use placement-new to construct the individual objects within those bytes. But now, you are having to manage not only the objects in the array, but also the byte array itself. By itself, unique_ptr<T[]> won't be able to free that byte array, so you would have to provide it with a custom deleter that frees the objects and the byte array. Which also means, you will have to keep track of how many objects are in the array (something new[] does for you so delete[] works, but you can't access that counter, so you will need your own), eg:
struct metadata_arr_deleter
{
void operator()(metadata_t *arr){
size_t count = *(reinterpret_cast<size_t*>(arr)-1);
for (size_t i = 0; i < count; ++i) {
arr[i]->~metadata_t();
}
delete[] reinterpret_cast<char*>(arr);
}
};
typedef std::unique_ptr<metadata_t[], metadata_arr_deleter> fixedsize_metadata_t;
fixedsize_metadata_t consolidate(const std::vector<metadata_t> &array) {
const auto n = array.size();
const size_t element_size = sizeof(std::aligned_storage_t<sizeof(metadata_t), alignof(metadata_t)>);
auto raw_bytes = std::make_unique<char[]>(sizeof(size_t) + (n * element_size));
size_t *ptr = reinterpret_cast<size_t*>(raw_bytes.get());
*ptr++ = n;
auto *uarr = reinterpret_cast<metadata_t*>(ptr);
size_t i = 0;
try {
for (i = 0; i < n; ++i) {
new (&uarr[i]) metadata_t(array[i]);
}
}
catch (...) {
for (size_t j = 0; j < i; ++j) {
uarr[j]->~metadata_t();
}
throw;
}
raw_bytes.release();
return fixedsize_metadata_t(uarr);
}
Needless to say, this puts much more responsibility on you to allocate and free memory correctly, and it is really just not worth the effort at this point. std::vector already supports everything you need. It can create an object array using a size known at runtime, and it can create non-default-constructable objects in that array, eg.
std::vector<metadata_t> consolidate(const std::vector<metadata_t> &array) {
auto n = array.size();
std::vector<metadata_t> varr;
varr.reserve(n);
for (const auto &elem : array) {
// either:
varr.push_back(elem);
// or:
varr.emplace_back(elem);
// it doesn't really matter in this case, since they
// will both copy-construct the new element in the array
// from the current element being iterated...
}
return varr;
}
Which is really just a less-efficient way of avoiding the vector's own copy constructor:
std::vector<metadata_t> consolidate(const std::vector<metadata_t> &array) {
return array; // will return a new copy of the array
}
The data structure does not have to be unique_ptr<T[]>. The old title referred to unique_ptr but I am really looking for a solution for a fixed-size data structure. So far, it is the only data structure I found as a "constant-size indexed container with size defined at runtime".
What you are looking for is exactly what std::vector already gives you. You just don't seem to realize it, or want to accept it. Both std::unique_ptr<T[]> and std::vector<T> hold a pointer to a dynamically-allocated array of a fixed size specified at runtime. It is just that std::vector offers more functionality than std::unique_ptr<T[]> does to manage that array (for instance, re-allocating the array to a different size). You don't have to use that extra functionality if you don't need it, but its base functionality will suit your needs just fine.
Initializing an array of non-default constructibles from a vector is tricky.
One way, if you know that your vector will never contain more than a certain amount of elements, could be to create an index_sequence covering all elements in the vector. There will be one instantiation of the template for each number of elements in your vector that you plan to support and the compilation time will be "silly".
Here I've selected the limit 512. It must have a limit, or else the compiler will spin in endless recursion until it gives up or crashes.
namespace detail {
template <class T, size_t... I>
auto helper(const std::vector<T>& v, std::index_sequence<I...>) {
if constexpr (sizeof...(I) > 512) { // max 512 elements in the vector.
return std::unique_ptr<T[]>{}; // return empty unique_ptr or throw
} else {
// some shortcuts to limit the depth of the call stack
if(sizeof...(I)+255 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+256>{});
if(sizeof...(I)+127 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+128>{});
if(sizeof...(I)+63 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+64>{});
if(sizeof...(I)+31 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+32>{});
if(sizeof...(I)+15 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+16>{});
if(sizeof...(I)+7 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+8>{});
if(sizeof...(I)+3 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+4>{});
if(sizeof...(I)+1 < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+2>{});
if(sizeof...(I) < v.size())
return helper(v, std::make_index_sequence<sizeof...(I)+1>{});
// sizeof...(I) == v.size(), create the pointer:
return std::unique_ptr<T[]>(new T[sizeof...(I)]{v[I]...});
}
}
} // namespace detail
template <class T>
auto make_unique_from_vector(const std::vector<T>& v) {
return detail::helper(v, std::make_index_sequence<0>{});
}
You can then turn your vector into a std::unique_ptr<metadata_t[]>:
auto up = make_unique_from_vector(foos);
if(up) {
// all is good
}
Demo (compilation time may exceed the time limit)
You have to allocate some uninitialized memory for an array and copy construct the elements in-place using construct_at. You can then create a unique_ptr using the address of the constructed array:
#include <vector>
#include <memory>
struct metadata_t {
metadata_t(int) { }
};
typedef std::unique_ptr<metadata_t[]> fixedsize_metadata_t;
fixedsize_metadata_t consolidate(const std::vector<metadata_t> &array) {
// note: this is run-time:
auto n = array.size();
std::allocator<metadata_t> alloc;
metadata_t *t = alloc.allocate(n);
for (std::size_t i = 0; i < array.size(); ++i) {
std::construct_at(&t[i], array[i]);
}
return fixedsize_metadata_t(t);
}
I need a 2d character array for use in a trash API that absolutely requires use of arrays and NOT vectors (much emphasis on this because all of my searching just had answers "use a vector". I wish I could).
I figured the way to do it would be to allocate an external array of size rows * character length, instead of doing:
char** arr;
arr = new char*[100];
// for loop that allocates the internal arrays
But I'm not sure what method I would need to use to make it contiguous? Do I need to allocate a massive 1D array first, then assign the 1D array to the 2D array in chunks?
As other answers have said: allocate n * m entries to create the contiguous data, and then it can be wrapped in pointers to create a 2d array.
... absolutely requires use of arrays and NOT vectors ...
I'm not sure if vector is a constraint based on the API being used, or requirements -- but it's worth noting that vector can be used for the memory management of the implementation -- while still using the raw data (which can be accessed by &vec[0] or vec.data(), which returns a pointer to the first element of the array, and can be used with functions accepting raw pointers).
Since this question is about c++, one option is to wrap an array of n * m in a class that acts like a 2-d array while actually being contiguous.
A simple example could be:
class array_2d
{
public:
array_2d( std::size_t rows, std::size_t columns )
: m_rows(rows), m_cols(columns), m_array( new char[rows * columns] )
{
}
~array_2d()
{
delete [] m_array;
}
// row-major vs column-major is up to your implementation
T& operator()( std::ptrdiff_t row, std::ptrdiff_t col )
{
// optional: do bounds checking, throw std::out_of_range first
return m_array[row * m_cols + col];
// alternatively:
// return m_array[col * m_rows + row];
}
// get pointer to the array (for raw calls)
char* data()
{
return m_array;
}
private:
char* m_array;
std::size_t m_rows;
std::size_t m_cols;
};
(Ideally char* would be std::unique_ptr<char[]> or std::vector<char> to avoid memory-leak conditions, but since you said vector is not viable, I'm writing this minimally)
This example overloads the call operator (operator()) -- but this could also be a named function like at(...); the choice would be up to you. The use of such type would then be:
auto array = array_2d(5,5); // create 5x5 array
auto& i01 = array(0,1); // access row 0, column 1
Optionally, if the [][] syntax is important to behave like a 2d-array (rather than the (r,c) syntax), you can return a proxy type from a call to an overloaded operator [] (untested):
class array_2d_proxy
{
public:
array_2d_proxy( char* p ) : m_entry(p){}
char& operator[]( std::ptrdiff_t col ){ return m_entry[col]; }
private:
char* m_entry;
};
class array_2d
{
...
array_2d_proxy operator[]( std::ptrdiff_t row )
{
return array_2d_proxy( m_array + (row * m_cols) );
}
...
};
This would allow you to have the 'normal' 2d-array syntax, while still being contiguous:
auto& i00 = array[0][0];
This is a good way to do it:
void array2d(int m, int n) {
std::vector<char> bytes(m * n);
std::vector<char*> arrays;
for (int i = 0; i != m * n; i += n) {
arrays.push_back(bytes.data() + i);
}
char** array2d = arrays.data();
// whatever
}
The main problem in C++ with "continuous 2d arrays with variable column length" is that an access like myArray[r][c] requires the compiler to know the column size of the type of myArray at compile time (unlike C, C++ does not support variable length arrays (VLAs)).
To overcome this, you could allocate a continuous block of characters, and additionally create an array of pointers, where each pointer points to the begin of a row. With such a "view", you can then address the continuous block of memory indirectly with a myArray[r][c]-notation:
int main() {
// variable nr of rows/columns:
int rows = 2;
int columns = 5;
// allocate continuous block of memory
char *contingousMemoryBlock = new char[rows*columns];
// for demonstration purpose, fill in some content
for (int i=0; i<rows*columns; i++) {
contingousMemoryBlock[i] = '0' + i;
}
// make an array of pointers as a 2d-"view" of the memory block:
char **arr2d= new char*[rows];
for (int r=0; r<rows;r++) {
arr2d[r] = contingousMemoryBlock + r*columns;
}
// access the continuous memory block as a 2d-array:
for (int r=0; r<rows; r++) {
for (int c=0; c<columns; c++) {
cout << arr2d[r][c];
}
cout << endl;
}
}
I have a problem described as below ::
class datad {
private:
int *a;
int _size;
vector<int> v;
public:
datad(int arr[], int size) {
_size = size;
for (int i = 0; i < size; i++)
a[i] = arr[i];
}
datad(vector<int> ve)
{
v = ve;
_size = ve.size();
}
void printdata()
{
// print data which the object has been initialized with
// if object is initialized with vector then print vector
// array print array
}
};
int main()
{
// print only vector data
int a[] = { 9,4,8,3,1,6,5 };
datad d(v1);
d.printdata();
// print only array data
datad d1(a, 7);
d1.printdata();
}
I need to find the way the object is initialized and then based on the same should be able to printdata accrodingly.
Can someone help me understand if it is possible at all?
Add a bool usesVector to your class and set it to true or false in each constructor as appropriate. Then, in printdata, simply check the value of the boolean.
Or you can set size to -1 in the vector case (as it's otherwise unused) and just check for that.
By the way, your array implementation is broken, because you never allocate any memory for it. You'd be much better off using only the vector version. You can still initialise that vector from array data if you wish.
You can set a flag in respective constructor and check that flag during the printing method.
I hope this is for learning purposes, otherwise as noted you maybe better of using just the vector version. When using dynamic memory management in class you need to be aware of things like rule of three and I guess there is also rule of five.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am working with a list of array in C++, each in an object and wanted to split some of them.
These are allocated dynamically.
I wanted to do the split in constant time as it is theoretically possible:
from
[ pointer, size1 ]
to
[ pointer, size2 ]; [ other array ]; [ pointer + size2, size1-size2 ]
(+ other data each time)
I tried to use malloc and simply create a new pointer incremented with the size.
As it could be expected, I got error due to the automatic freeing of the memory.
I tried a realloc starting at the second address, but as in "what is the difference between malloc and calloc" on this site already told me it is not possible.
Is there a way to avoid recopying the second part and define correctly the pointer?
Having a linear cost where I know I can have constant time is frustrating.
class TableA
{
public:
(constructor)
void divide(int size); // the one i am trying to implement
(other, geteur, seteur)
private
Evenement* _el;
vector<bool>** _old;//said arrays
int _size;
}
nothing really complicated
Basically, the malloc library can't cope with mallocing a chunk of memory and then freeing it slices.
You can do what you want, but you must only free the memory all at once right at the end using the original pointer that malloc handed you.
e.g.
int* p = malloc(9 * sizeof(int));
int* q = p + 3;
int* r = p + 6;
// Now we have three pointers to three arrays of three integers.
// Do stuff with p, q, r
free(p); // p is the only pointer it is valid to free.
By the way, if this is really about C++, there are probably standard C++ data structures you can use.
I don't think you can have only part of a dynamic array freed by keeping track of pointers and length. However, you can fake this by making a new class to manage the starting array, allocate it however you want and have it managed by a std::shared_ptr.
You simply return a Class containing a shared_ptr to memory, plain pointer to first element, and array size. When the current Array class goes out of scope, the shared_ptr gets decremented, and when no slices of the memory are used anymore, the memory gets freed.
You need to be careful with this though, as there may be multiple objects referencing the same memory, but there's ways around that (marking the original invalid after splitting with a bool for example).
[Edit] Below is a very basic implementation of this idea. A split() operator can very easily be implemented in terms of 2 slice() operations. I'm not sure how you want to implement this in terms of your example above, as I'm not sure how you manage your vector<bool> **, but if you wanted the possibility of splitting your vector<bool>, you could instantiate a ShareVector<bool>, or if you have an array of vector<bool>, your make a SharedVector<vector<bool>> instead.
#ifndef __SharedVector__
#define __SharedVector__
#include <memory>
#include <assert.h>
template <typename T>
class SharedVector {
std::shared_ptr<T> _data;
T *_begin;
size_t _size;
// perhaps add size_t capacity if need for limited resizing arises.
public:
SharedVector<T>(size_t const size)
: _data(std::shared_ptr<T>(new T[size], []( T *p ) { delete[] p; })), _begin(_data.get()), _size(size)
{}
// standard copy and move constructors work fine
// pass shared_ptr by reference to avoid unnecessary refcount changes
SharedVector<T>(std::shared_ptr<T> &data, T *begin, size_t size)
: _data(data), _begin(begin), _size(size)
{}
T& operator[] (const size_t nIndex) {
assert(nIndex < _size);
return _begin[nIndex];
}
T const & operator[] (const size_t nIndex) const {
assert(nIndex < _size);
return _begin.get()[nIndex];
}
size_t size(){
return _size;
}
SharedVector<T> slice(size_t const begin, size_t const end) {
assert(begin + end < _size);
return SharedVector<T>(_data, _begin + begin, end - begin);
}
T *begin() {
return _begin;
}
T *end() {
return _begin + _size;
}
};
#endif
I think the malloc and create new pointer idea is good. But you need to free the memory manually I think.
Maybe you can use std::copy.
int* p = (int*)malloc(sizeof(int) * 5);
for (int i = 0; i < 5; i++)
p[i] = i;
for (int i = 0; i < 5; i++)
std::cout << p[i];
// tmp will hold 3 values
// p2 will hold 2 values
// so we want to copy first 3 into tmp
// and last 2 into p2
int tmp[3];
std::copy(p, p+3, tmp);
for (int i = 0; i < 3; i++)
std::cout << tmp[i];
int p2[2];
std::copy(p+3, p+5, p2);
for (int i = 0; i < 2; i++)
std::cout << p2[i];
// get rid of original when done
free(p);
Output:
0123401234
The question is relatively unclear
But according to your topic
splitting dynamically allocated array without linear time copy
i would suggest you to use linked list instead of an array, you don't need to copy anything (and therefore no need to free anything UNLESS you wanna delete one of the item), manipulating the pointers would be sufficient for splitting a linked list
as in the title is it possible to join a number of arrays together without copying and only using pointers? I'm spending a significant amount of computation time copying smaller arrays into larger ones.
note I can't used vectors since umfpack (some matrix solving library) does not allow me to or i don't know how.
As an example:
int n = 5;
// dynamically allocate array with use of pointer
int *a = new int[n];
// define array pointed by *a as [1 2 3 4 5]
for(int i=0;i<n;i++) {
a[i]=i+1;
}
// pointer to array of pointers ??? --> this does not work
int *large_a = new int[4];
for(int i=0;i<4;i++) {
large_a[i] = a;
}
Note: There is already a simple solution I know and that is just to iteratively copy them to a new large array, but would be nice to know if there is no need to copy repeated blocks that are stored throughout the duration of the program. I'm in a learning curve atm.
thanks for reading everyone
as in the title is it possible to join a number of arrays together without copying and only using pointers?
In short, no.
A pointer is simply an address into memory - like a street address. You can't move two houses next to each other, just by copying their addresses around. Nor can you move two houses together by changing their addresses. Changing the address doesn't move the house, it points to a new house.
note I can't used vectors since umfpack (some matrix solving library) does not allow me to or i don't know how.
In most cases, you can pass the address of the first element of a std::vector when an array is expected.
std::vector a = {0, 1, 2}; // C++0x initialization
void c_fn_call(int*);
c_fn_call(&a[0]);
This works because vector guarantees that the storage for its contents is always contiguous.
However, when you insert or erase an element from a vector, it invalidates pointers and iterators that came from it. Any pointers you might have gotten from taking an element's address no longer point to the vector, if the storage that it has allocated must change size.
No. The memory of two arrays are not necessarily contiguous so there is no way to join them without copying. And array elements must be in contiguous memory...or pointer access would not be possible.
I'd probably use memcpy/memmove, which is still going to be copying the memory around, but at least it's been optimized and tested by your compiler vendor.
Of course, the "real" C++ way of doing it would be to use standard containers and iterators. If you've got memory scattered all over the place like this, it sounds like a better idea to me to use a linked list, unless you are going to do a lot of random access operations.
Also, keep in mind that if you use pointers and dynamically allocated arrays instead of standard containers, it's a lot easier to cause memory leaks and other problems. I know sometimes you don't have a choice, but just saying.
If you want to join arrays without copying the elements and at the same time you want to access the elements using subscript operator i.e [], then that isn't possible without writing a class which encapsulates all such functionalities.
I wrote the following class with minimal consideration, but it demonstrates the basic idea, which you can further edit if you want it to have functionalities which it's not currently having. There should be few error also, which I didn't write, just to make it look shorter, but I believe you will understand the code, and handle error cases accordingly.
template<typename T>
class joinable_array
{
std::vector<T*> m_data;
std::vector<size_t> m_size;
size_t m_allsize;
public:
joinable_array() : m_allsize() { }
joinable_array(T *a, size_t len) : m_allsize() { join(a,len);}
void join(T *a, size_t len)
{
m_data.push_back(a);
m_size.push_back(len);
m_allsize += len;
}
T & operator[](size_t i)
{
index ix = get_index(i);
return m_data[ix.v][ix.i];
}
const T & operator[](size_t i) const
{
index ix = get_index(i);
return m_data[ix.v][ix.i];
}
size_t size() const { return m_allsize; }
private:
struct index
{
size_t v;
size_t i;
};
index get_index(size_t i) const
{
index ix = { 0, i};
for(auto it = m_size.begin(); it != m_size.end(); it++)
{
if ( ix.i >= *it ) { ix.i -= *it; ix.v++; }
else break;
}
return ix;
}
};
And here is one test code:
#define alen(a) sizeof(a)/sizeof(*a)
int main() {
int a[] = {1,2,3,4,5,6};
int b[] = {11,12,13,14,15,16,17,18};
joinable_array<int> arr(a,alen(a));
arr.join(b, alen(b));
arr.join(a, alen(a)); //join it again!
for(size_t i = 0 ; i < arr.size() ; i++ )
std::cout << arr[i] << " ";
}
Output:
1 2 3 4 5 6 11 12 13 14 15 16 17 18 1 2 3 4 5 6
Online demo : http://ideone.com/VRSJI
Here's how to do it properly:
template<class T, class K1, class K2>
class JoinArray {
JoinArray(K1 &k1, K2 &k2) : k1(k1), k2(k2) { }
T operator[](int i) const { int s = k1.size(); if (i < s) return k1.operator[](i); else return k2.operator[](i-s); }
int size() const { return k1.size() + k2.size(); }
private:
K1 &k1;
K2 &k2;
};
template<class T, class K1, class K2>
JoinArray<T,K1,K2> join(K1 &k1, K2 &k2) { return JoinArray<T,K1,K2>(k1,k2); }
template<class T>
class NativeArray
{
NativeArray(T *ptr, int size) : ptr(ptr), size(size) { }
T operator[](int i) const { return ptr[i]; }
int size() const { return size; }
private:
T *ptr;
int size;
};
int main() {
int array[2] = { 0,1 };
int array2[2] = { 2,3 };
NativeArray<int> na(array, 2);
NativeArray<int> na2(array2, 2);
auto joinarray = join(na,na2);
}
A variable that is a pointer to a pointer must be declared as such.
This is done by placing an additional asterik in front of its name.
Hence, int **large_a = new int*[4]; Your large_a goes and find a pointer, while you've defined it as a pointer to an int. It should be defined (declared) as a pointer to a pointer variable. Just as int **large_a; could be enough.