'C++: Append to front, add to back array of int's
I have the following array:
int a1[] = {1,2,3,4,5,6};
I would like to know how can I append any number to the front, and to the back of this array. In JavaScript, there is unshift() and push(). Is there anything like that in C++?
Solution 1:[1]
In C++, arrays are a kind of type, and the array size is part of the type. Therefore, the size of an array object is part of this object's type and not modifiable at runtime.
To manage dynamic collections of objects in C++, you would usually use a container class. There are several useful containers included in the standard library; the most important one is std::vector, which manages a dynamic, contiguously stored sequence of elements — essentially a resizable array!
A JavaScript array is much closer to a C++ vector (or perhaps to a hash map) than to a C++ array.
Solution 2:[2]
You can't do it directly, but if you like, you can write a simple code to manage it:
#include <stdlib.h>
#include<stdarg.h>
#include <iostream>
using namespace std;
typedef struct int_array
{
int *ptr;
int len;
int_array(int n_args, ...)
{
ptr = NULL;
len = 0;
va_list ap;
va_start(ap, n_args);
for (int i = 1; i <= n_args; i++) {
push(va_arg(ap, int));
}
va_end(ap);
}
int operator[](int idx) const
{
return ptr[idx];
}
void push(int value)
{
ptr = (int*)(len ? realloc(ptr, (len + 1)*sizeof(int)) : malloc(sizeof((len + 1))));
ptr[len++] = value;
}
void unshift(int value)
{
ptr = (int*)(len ? realloc(ptr, (len+1)*sizeof(int)) : malloc(sizeof(len+1)));
for (int i = len++; i > 0; i--)
{
ptr[i] = ptr[i-1];
}
ptr[0] = value;
}
}IntArray;
int main(int argc, char** argv)
{
IntArray arr(6/* initial len */, 1, 2, 3, 4, 5, 6);
arr.push(7);
arr.push(8);
arr.unshift(0);
arr.unshift(-1);
for (int i = 0; i < arr.len;i++)
{
cout << arr[i] << endl;
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kerrek SB |
| Solution 2 | Ehsan Khodarahmi |
