Return a 2d array from a function - c++

Hi I am a newbie to C++
I am trying to return a 2d array from a function.
It is something like this
int **MakeGridOfCounts(int Grid[][6])
{
int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
return cGrid;
}

This code returns a 2d array.
#include <cstdio>
// Returns a pointer to a newly created 2d array the array2D has size [height x width]
int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
// important: clean up memory
printf("\n");
printf("Cleaning up memory...\n");
for (int h = 0; h < height; h++) // loop variable wasn't declared
{
delete [] my2DArray[h];
}
delete [] my2DArray;
my2DArray = 0;
printf("Ready.\n");
return 0;
}

A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation.
std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}

That code isn't going to work, and it's not going to help you learn proper C++ if we fix it. It's better if you do something different. Raw arrays (especially multi-dimensional arrays) are difficult to pass correctly to and from functions. I think you'll be much better off starting with an object that represents an array but can be safely copied. Look up the documentation for std::vector.
In your code, you could use vector<vector<int> > or you could simulate a 2-D array with a 36-element vector<int>.

What you are (trying to do)/doing in your snippet is to return a local variable from the function, which is not at all recommended - nor is it allowed according to the standard.
If you'd like to create a int[6][6] from your function you'll either have to allocate memory for it on the free-store (ie. using new T/malloc or similar function), or pass in an already allocated piece of memory to MakeGridOfCounts.

The function returns a static 2D array
const int N = 6;
int (*(MakeGridOfCounts)())[N] {
static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
return cGrid;
}
int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}
You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.

#include <iostream>
using namespace std ;
typedef int (*Type)[3][3] ;
Type Demo_function( Type ); //prototype
int main (){
cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"
int array[3][3] ;
Type recieve , ptr = &array;
recieve = Demo_function( ptr ) ;
for ( int i = 0 ; i < 3 ; i ++ ){
for ( int j = 0 ; j < 3 ; j ++ ){
cout << (*recieve)[i][j] << " " ;
}
cout << endl ;
}
return 0 ;
}
Type Demo_function( Type array ){/*function definition */
cout << "Enter values : \n" ;
for (int i =0 ; i < 3 ; i ++)
for ( int j = 0 ; j < 3 ; j ++ )
cin >> (*array)[i][j] ;
return array ;
}

Whatever changes you would make in function will persist.So there is no need to return anything.You can pass 2d array and change it whenever you will like.
void MakeGridOfCounts(int Grid[][6])
{
cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
}
or
void MakeGridOfCounts(int Grid[][6],int answerArray[][6])
{
....//do the changes in the array as you like they will reflect in main...
}

int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main ()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
return 0;
}

returning an array of pointers pointing to starting elements of all rows is the only decent way of returning 2d array.

I would suggest you Matrix library as an open source tool for c++, its usage is like arrays in c++. Here you can see documention.
Matrix funcionName(){
Matrix<int> arr(2, 2);
arr[0][0] = 5;
arr[0][1] = 10;
arr[1][0] = 0;
arr[1][1] = 44;
return arr;
}

Related

how to return 2d array using pointers [duplicate]

Hi I am a newbie to C++
I am trying to return a 2d array from a function.
It is something like this
int **MakeGridOfCounts(int Grid[][6])
{
int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
return cGrid;
}
This code returns a 2d array.
#include <cstdio>
// Returns a pointer to a newly created 2d array the array2D has size [height x width]
int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
// important: clean up memory
printf("\n");
printf("Cleaning up memory...\n");
for (int h = 0; h < height; h++) // loop variable wasn't declared
{
delete [] my2DArray[h];
}
delete [] my2DArray;
my2DArray = 0;
printf("Ready.\n");
return 0;
}
A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation.
std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}
That code isn't going to work, and it's not going to help you learn proper C++ if we fix it. It's better if you do something different. Raw arrays (especially multi-dimensional arrays) are difficult to pass correctly to and from functions. I think you'll be much better off starting with an object that represents an array but can be safely copied. Look up the documentation for std::vector.
In your code, you could use vector<vector<int> > or you could simulate a 2-D array with a 36-element vector<int>.
What you are (trying to do)/doing in your snippet is to return a local variable from the function, which is not at all recommended - nor is it allowed according to the standard.
If you'd like to create a int[6][6] from your function you'll either have to allocate memory for it on the free-store (ie. using new T/malloc or similar function), or pass in an already allocated piece of memory to MakeGridOfCounts.
The function returns a static 2D array
const int N = 6;
int (*(MakeGridOfCounts)())[N] {
static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
return cGrid;
}
int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}
You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.
#include <iostream>
using namespace std ;
typedef int (*Type)[3][3] ;
Type Demo_function( Type ); //prototype
int main (){
cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"
int array[3][3] ;
Type recieve , ptr = &array;
recieve = Demo_function( ptr ) ;
for ( int i = 0 ; i < 3 ; i ++ ){
for ( int j = 0 ; j < 3 ; j ++ ){
cout << (*recieve)[i][j] << " " ;
}
cout << endl ;
}
return 0 ;
}
Type Demo_function( Type array ){/*function definition */
cout << "Enter values : \n" ;
for (int i =0 ; i < 3 ; i ++)
for ( int j = 0 ; j < 3 ; j ++ )
cin >> (*array)[i][j] ;
return array ;
}
Whatever changes you would make in function will persist.So there is no need to return anything.You can pass 2d array and change it whenever you will like.
void MakeGridOfCounts(int Grid[][6])
{
cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
}
or
void MakeGridOfCounts(int Grid[][6],int answerArray[][6])
{
....//do the changes in the array as you like they will reflect in main...
}
int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main ()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
return 0;
}
returning an array of pointers pointing to starting elements of all rows is the only decent way of returning 2d array.
I would suggest you Matrix library as an open source tool for c++, its usage is like arrays in c++. Here you can see documention.
Matrix funcionName(){
Matrix<int> arr(2, 2);
arr[0][0] = 5;
arr[0][1] = 10;
arr[1][0] = 0;
arr[1][1] = 44;
return arr;
}

Porting code from C++ to C. How do I deal with this vector and range based loop

I am trying to port to C. Since there's no vectors in C, I used a normal array, but I don't know how I'm going to deal with the ranged based loop on line 18.
for (int u : d[i]) if (dfs(rev[u])) {
par[i] = u;
rev[u] = i;
return true;
}
Complete code:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
const int Maxn = 200;
vector<int> d[Maxn];
int par[Maxn];
int rev[Maxn];
bool vs[Maxn];
bool dfs(int i) {
if (i < 0) return true;
if (vs[i]) return false;
vs[i] = true;
for (int u : d[i]) if (dfs(rev[u])) {
par[i] = u;
rev[u] = i;
return true;
}
return false;
}
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
string s;
getline(cin, s);
for (int i = 0; i < n; i++) {
getline(cin, s);
stringstream ss(s);
vector<int> mk(n, 1);
mk[i] = 0;
int x;
while (ss >> x)
mk[x] = 0;
for (int x = 0; x < n; x++)
if (mk[x])
d[i].push_back(x);
}
memset(par, -1, sizeof par);
memset(rev, -1, sizeof rev);
for (bool ok = true; ok; ) {
ok = false;
memset(vs, 0, sizeof vs);
for (int i = 0; i < n; i++)
if (par[i] < 0) {
ok |= dfs(i);
}
}
int ans = 0;
for (int i = 0; i < n; i++)
ans += (par[i] < 0);
cout << ans;
}
In C there is no std::vector, the closes would be an array.
int array[] = [ 1, 3, 5, 7, 9 ];
for(int i = 0; i < sizeof array / sizeof *array; ++i)
printf("array[%d] = %d\n", i, array[i]);
If you get a pointer of an array of int, the you have to pass the length of
the array as well, as sizeof arr / sizeof *arr works with arrays only.
void foo(in *array, size_t len)
{
for(int i = 0; i < len; ++i)
printf("array[%d] = %d\n", i, array[i]);
}
void bar(void)
{
int array[] = [ 1, 3, 5, 7, 9 ];
foo(array, sizeof array / sizeof *array);
}
edit 2
I noticed that you've posted your code and that d is declared as vector<int> d[Maxn];. Also taking in consideration your recent comment
So this is an array of vectors. Do you have any idea how i can work with arrays taking that in consideration in C
There a couple of ways to convert the array of vectors in C. But this depends
on your needs. If for example you know that all vectors are going to have the
same size (for example int vectsize = 100), then you can create a two
dimensional array with the sizes1
int Maxn = 200;
int vectsize = 100;
int d[Maxn][vectsize];
memset(d, 0, sizeof d); // initialize all elements with 0
// filling the data
for(int i = 0; i < Maxn; ++i)
{
for(j = 0; j < vectsize; ++j)
d[i][j] = get_value_for(i, j);
}
The the range-loop is very easy:
// assuming that the variables i, par, rev are valid, i between 0 and Maxn-1
for(int j = 0; j < vectsize; ++j)
{
int u = d[i][j];
if (dfs(rev[u])) {
par[i] = u;
rev[u] = i;
return true;
}
}
It gets a little more complicated if you only know one dimension, for example
every vector in the array could have a different size.
d[0].size() --> 10
d[1].size() --> 1
d[2].size() --> 3
...
The you can create an array of pointers to int, but you would have to keep
another array of ints with the length for every d[i] vector.
int Maxn = 200;
int *d[Maxn]; // pointer to int[Maxn] arrays
int vectsize[Maxn];
// initializing with 0
memset(d, 0, sizeof d);
memset(vectsize, 0, sizeof vectsize);
// filling the data
for(int i = 0; i < Maxn; ++i)
{
vectsize[i] = get_length_for(i);
d[i] = malloc(vectsize[i] * sizeof *d[i]);
if(d[i] == NULL)
// error handling
for(j = 0; j < vectsize[i]; ++j)
d[i][j] = get_value_for(i, j);
}
Note that I'm using here (and in the last example) get_length_for() and get_value_for() as placeholders2.
Now your range-base loop would look like this:
// assuming that the variables i, par, rev are valid, i between 0 and Maxn-1
for(int j = 0; j < vectsize[i]; ++j)
{
int u = d[i][j];
if (dfs(rev[u])) {
par[i] = u;
rev[u] = i;
return true;
}
}
At some point however you would have to free the memory:
for(int i = 0; i < Maxn; ++i)
free(d[i]);
The third option would be using a double pointer and using malloc/realloc
to allocate the memory. This is the more general solution, but you have to
take care of memory management and that can be sometimes difficult, especially when you
haven't programmed in C to much. But also in case where both dimension are unknown, this is the way to go:
int Maxn = get_some_maxn_value();
int **d, *vectsize;
d = malloc(Maxn * sizeof *d);
if(d == NULL)
// error handling
vectsize = malloc(Maxn * sizeof *vectsize);
if(vectsize == NULL)
// error handling,
// if you exit the function, don't forget
// to do free(d) first as part of the
// error handling
// initialize all elements with 0
memset(d, 0, Maxn * sizeof *d);
memset(vectsize, 0, Maxn * sizeof *vectsize);
// filling the data (the same as above)
for(int i = 0; i < Maxn; ++i)
{
vectsize[i] = get_length_for(i);
d[i] = malloc(vectsize[i] * sizeof *d[i]);
if(d[i] == NULL)
// error handling
for(j = 0; j < vectsize[i]; ++j)
d[i][j] = get_value_for(i, j);
}
In this case the range-loop would look exactly as for the array of pointers.
Freeing the memory is a little bit different though:
for(int i = 0; i < Maxn; ++i)
free(d[i]);
free(d);
free(vectsize);
Like I said earlier, which one of these three methods to use depends on the way
the original C++ code fills the values, how long the vectors are, etc. Judging
form the C++ code you posted, you read an integer from the user and store it
in n. Then you read more values from the user and push then in the vector
d[i] for all i between 0 and Maxn-1. It seems that all vectors have at
most length n, but because of
if (mk[x])
d[i].push_back(x);
they also could have less than n elements. That's why I think that the third
solution is preferable here.
Annotations
1Prior to C99, Variable Length Arrays (VLA) were not supported, so if you had the
dimension in a variable, you had to use malloc to allocate enough memory.
C99 supports VLAs, but I'm not quite sure how well supported they are and/or
whether your compiler supports them.
I personally don't use them in my code at all, that's why I really don't know. I compiled this examples with GNU
GCC 6.4.0 (on linux) and they worked fine.
The first two options use VLAs, if your compiler doesn't support that, then
you have to use the third option.
For more information about VLAs:
malloced array VS. variable-length-array
What's the difference between a VLA and dynamic memory allocation via malloc?
Variable length array
GCC manual: 6.19 Arrays of Variable Length (in case you ise GCC)
2How you really get this values depends on the original C++ code.
So far I've only looked very briefly over your C++ code. Using the values from
my example get_length_for(0) would return 10, get_length_for(1) would return 1,
get_length_for(2) would return 3, etc.
Assuming d[i] is a vector, this is a similar loop:
for (size_t s = 0; s < d[i].size(); s++)
{
int u = d[i][s];
if (dfs(rev[u]))
{
par[i] = u;
rev[u] = i;
return true;
}
}

C++ vector values keep changing?

This is a real simple problem. I'm writing a sliding block puzzle game for an exercise.
1, 1, 1, 1, 1,
1, 0, 3, 4, 1,
1, 0, 2, 2, 1,
1, 1, 1, 1, 1,
It receives input as in the form above, with '0' representing empty spaces, '1' representing walls, and all other numbers representing blocks.
Here is the class definition and constructor for the game state:
class GameState {
public:
GameState(int hght, int wdth);
GameState(const GameState &obj);
~GameState();
int getHeight();
int getWidth();
int getElem(int i, int j);
void setElem(int i, int j, int val);
void display();
void readFile(char* filename);
bool checkSolved();
map<int, vector<int*> > blockLocations;
vector<int> blockList;
void getBlockLocations();
void findBlock(int n);
private:
int **grid;
int height, width;
void allocate() {
grid = new int*[height];
for(int i = 0; i < height; i++)
{
grid[i] = new int[width];
}
}
};
GameState::GameState(int hght, int wdth) {
height = hght;
width = wdth;
allocate();
for(int i = 0; i < hght; i++) {
for (int j = 0; j < wdth; j++) {
grid[i][j] = 0;
}
}
};
Essentially, the grid is represented by a two-dimensional pointer array of integers. height and width are self-explanatory; blockLocations is a map that maps a block number to its point-wise coordinates of the form (y, x). For the time being, if a block occupies multiple spaces only the lowest rightmost space is listed. The matrix initializes as being nothing but zeros; the actual values are read in from a csv.
All of these methods are defined, but the two methods of concern are getBlockLocations() and findBlock(int n).
void GameState::getBlockLocations() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
blockList.push_back(grid[i][j]);
int pos[2] = {i, j};
vector<int*> v;
v.push_back(pos);
blockLocations[grid[i][j]] = v;
}
}
}
void GameState::findBlock(int n) {
vector<int>::iterator it;
it = find(blockList.begin(), blockList.end(), n);
if (it != blockList.end()) {
vector<int*> * posList = &blockLocations[n];
for (int itr = 0; itr < posList->size(); itr++) {
vector<int*> curPos = *posList;
cout << curPos[itr][0] << ", " << curPos[itr][1] << endl;
}
}
}
The problem comes up when I actually run this. As a case example, when I run getBlockLocations(), it correctly stores the coordinate for '2' as (2, 3). However, when I ask the program to display the location of that block with findBlock(2), the resulting output is something along the lines of (16515320, 0). It's different every time but never correct. I don't see the pointer mistake I'm making to get incorrect values like this.
That is bad:
for (int j = 0; j < width; j++) {
blockList.push_back(grid[i][j]);
int pos[2] = {i, j};
vector<int*> v;
v.push_back(pos);
blockLocations[grid[i][j]] = v;
}
You create a pos variable locally and store its reference. When you go out of scope of the for loop it is invalid / data can be replaced by something else.
(actually as Barmar pointed out, since the pos address is always the same within the loop, the values change at each iteration)
You could use a std::pair<int,int> to store your values instead.
When you insert the pair in the vector, the data is copied, not only the pointer: it is safe.
typedef std::pair<int,int> IntIntPair;
IntIntPair pos(i,j);
std::vector<IntIntPair> v;

how do I allocate one block of memory with new?

I have a two dimensional array that I've allocated dynamically using new.
The problem is I want to allocate the memory as one connected block instead of in separated pieces to increase processing speed.
Does anyone know if it's possible to do this with new, or do I have to use malloc?
Here's my code:
A = new double*[m];
for (int i=0;i<m;i++)
{
A[i]= new double[n];
}
This code causes a segmentation fault
phi = new double**[xlength];
phi[0] = new double*[xlength*ylength];
phi[0][0] = new double[xlength*ylength*tlength];
for (int i=0;i<xlength;i++)
{
for (int j=0;j<ylength;j++)
{
phi[i][j] = phi[0][0] + (ylength*i+j)*tlength;
}
phi[i] = phi[0] + ylength*i;
}
You can allocate one big block and use it appropriately, something like this:
double* A = new double[m*n];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
A[i*n+j] = <my_value>;
}
}
Instead of using new, you can use malloc - there is no much difference, except that new must be released with delete, and malloc() released with free().
UPDATE1:
You can create "true" 2d array as follows:
double** A = new double*[m];
double* B = new double[m*n];
for (int i=0; i<m; i++) {
A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
A[i][j] = <my_value>;
}
}
Just be sure to release both A and B in the end.
UPDATE2:
By popular request, this is how you can create "true" 3-dimensional array (with dimensions m x n x o):
double*** A = new double**[m];
double** B = new double*[m*n];
double* C = new double[m*n*o];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
B[n*i+j] = C + (n*i+j)*o;
}
A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
for (int k=0; k<o; k++) {
A[i][j][k] = <my_value>;
}
}
}
This uses 2 relatively small "index" arrays A and B, and data array C. As usual, all three should be released after use.
Extending this for more dimensions is left as an exercise for the reader.
There is nothing you can do with malloc that you can't do with new (though the converse doesn't hold). However if you've already allocated the memory in separate blocks, you will have to allocate new (contiguous) memory in order to get a connected block (with either malloc or new). The code you show allocates m non-contiguous n-sized blocks. To get an array with contiguous memory from this, you would need
int MN = m*n;
B = new double[MN];
for (int i=0; i<MN; ++i)
B[i] = A[ i/N ] [ i%N ];
Ok, if the task is to maintain a single block of memory, but keep [][] way of addressing it, I'd try a few tricks with classes. The first one is an inside proxy:
class CoordProxy
{
private:
int coordX;
int arrayWidth;
int * dataArray;
public:
CoordProxy(int * newArray, int newArrayWidth, int newCoordX)
{
coordX = newCoordX;
arrayWidth = newArrayWidth;
dataArray = newArray;
}
int & operator [](int newCoordY)
{
return (dataArray[newCoordY * arrayWidth + coordX]);
}
};
class CoordsWrapper
{
private:
int * dataArray;
int width;
int height;
public:
CoordsWrapper(int * newArray, int newWidth, int newHeight)
{
dataArray = newArray;
width = newWidth;
height = newHeight;
}
CoordProxy operator[] (int coordX)
{
return CoordProxy(dataArray, width, coordX);
}
};
int main(int argc, char * argv[])
{
int * a = new int[4 * 4];
ZeroMemory(a, 4 * 4 * sizeof(int));
CoordsWrapper w(a, 4, 4);
w[0][0] = 10;
w[0][1] = 20;
w[3][3] = 30;
std::for_each(&a[0], &a[4 * 4], [](int x) { printf("%d ", x); });
delete[] a;
}
Note, that this is not time-efficient, but extremely memory efficient: uses 4 ints and 2 pointers more than original class.
There's even nicer and a lot faster solution, but you would have to resign from [][] notation in favor of (,) notation:
class CoordsWrapper2
{
private:
int * data;
int width;
int height;
public:
CoordsWrapper2(int * newData, int newWidth, int newHeight)
{
data = newData;
width = newWidth;
height = newHeight;
}
inline int & Data(int x, int y)
{
return data[y * width + x];
}
};
int main(int argc, char * argv[])
{
int * a = new int[4 * 4];
ZeroMemory(a, 4 * 4 * sizeof(int));
CoordsWrapper2 w(a, 4, 4);
w.Data(0, 0) = 10;
w.Data(0, 1) = 20;
w.Data(3, 3) = 30;
std::for_each(&a[0], &a[4 * 4], [](int x) { printf("%d ", x); });
delete[] a;
}
Note the inline directive. It suggests the compiler to replace the method call for actual source code, which make it a little faster. This solution is even more memory efficient and a either a tiny bit less or equally time efficient as classic indexing.

How does one rank an array (sort) by value? *With a twist*

I would like to sort an array in ascending order using C/C++. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.
Example
Input: 1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
Edit: I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.
Update:
Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.
Could someone please tell me what's wrong?
I'd very much appreciate some help!
void SortArray(int ** pArray, int ArrayLength)
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for (i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength - 1); j++)
{
if (*pArray[j + 1] > *pArray[j]) // ascending order simply changes to <
{
&temp = &pArray[j]; // swap elements
&pArray[j] = &pArray[j + 1]; //the problem lies somewhere in here
&pArray[j + 1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
};
Since you're using C++, I would do it something like this. The SortIntPointers function can be any sort algorithm, the important part is that it sorts the array of pointers based on the int that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which will end up in the original position in the original array.
int* intArray; // set somewhere else
int arrayLen; // set somewhere else
int** pintArray = new int*[arrayLen];
for(int i = 0; i < arrayLen; ++i)
{
pintArray[i] = &intArray[i];
}
// This function sorts the pointers according to the values they
// point to. In effect, it sorts intArray without losing the positional
// information.
SortIntPointers(pintArray, arrayLen);
// Dereference the pointers and assign their sorted position.
for(int i = 0; i < arrayLen; ++i)
{
*pintArray[i] = i;
}
Hopefully that's clear enough.
Ok, here is my atempt in C++
#include <iostream>
#include <algorithm>
struct mycomparison
{
bool operator() (int* lhs, int* rhs) {return (*lhs) < (*rhs);}
};
int main(int argc, char* argv[])
{
int myarray[] = {1, 3, 6, 2, 4, 9, 5, 12, 10};
const size_t size = sizeof(myarray) / sizeof(myarray[0]);
int *arrayofpointers[size];
for(int i = 0; i < size; ++i)
{
arrayofpointers[i] = myarray + i;
}
std::sort(arrayofpointers, arrayofpointers + size, mycomparison());
for(int i = 0; i < size; ++i)
{
*arrayofpointers[i] = i + 1;
}
for(int i = 0; i < size; ++i)
{
std::cout << myarray[i] << " ";
}
std::cout << std::endl;
return 0;
}
create a new array with increasing values from 0 to n-1 (where n is the length of the array you want to sort). Then sort the new array based on the values in the old array indexed by the values in the new array.
For example, if you use bubble sort (easy to explain), then instead of comparing the values in the new array, you compare the values in the old array at the position indexed by a value in the new array:
function bubbleRank(A){
var B = new Array();
for(var i=0; i<A.length; i++){
B[i] = i;
}
do{
swapped = false;
for(var i=0; i<A.length; i++){
if(A[B[i]] > A[B[i+1]]){
var temp = B[i];
B[i] = B[i+1];
B[i+1] = temp;
swapped = true;
}
}
}while(swapped);
return B;
}
create a new Array and use bubble sort to rank the elements
int arr[n];
int rank[n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(arr[i]>arr[j])
rank[i]++;
The rank of each element will be rank[i]+1 to be in the order of 1,2,....n
Well, there's a trival n^2 solution.
In python:
newArray = sorted(oldArray)
blankArray = [0] * len(oldArray)
for i in xrange(len(newArray)):
dex = oldArray.index(newArray[i])
blankArray[dex] = i
Depending on how large your list is, this may work. If your list is very long, you'll need to do some strange parallel array sorting, which doesn't look like much fun and is a quick way to introduce extra bugs in your code.
Also note that the above code assumes unique values in oldArray. If that's not the case, you'll need to do some post processing to solve tied values.
Parallel sorting of vector using boost::lambda...
std::vector<int> intVector;
std::vector<int> rank;
// set up values according to your example...
intVector.push_back( 1 );
intVector.push_back( 3 );
intVector.push_back( 4 );
intVector.push_back( 9 );
intVector.push_back( 6 );
for( int i = 0; i < intVector.size(); ++i )
{
rank.push_back( i );
}
using namespace boost::lambda;
std::sort(
rank.begin(), rank.end(),
var( intVector )[ _1 ] < var( intVector )[ _2 ]
);
//... and because you wanted to replace the values of the original with
// their rank
intVector = rank;
Note: I used vectorS instead of arrays because it is clearer/easier, also, I used C-style indexing which starts counting from 0, not 1.
This is a solution in c language
#include <stdio.h>
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
/* Function to print an array */
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 98};
int arr_original[] = {64, 34, 25, 12, 22, 11, 98};
int rank[7];
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
//PLACE RANK
//look for location of number in original array
//place the location in rank array
int counter = 1;
for (int k = 0; k < n; k++){
for (int i = 0; i < n; i++){
printf("Checking..%d\n", i);
if (arr_original[i] == arr[k]){
rank[i] = counter;
counter++;
printf("Found..%d\n", i);
}
}
}
printf("Original array: \n");
printArray(arr_original, n);
printf("Rank array: \n");
printArray(rank, n);
return 0;
}