Initialising array from a variable (C++) - c++

Im currently doing a programming project, and I've come across a problem while compiling... I have this code made in C++:
scanf("%d %d", &number, &shares);
vector<int> graph[number];
I read the variable number, and use it to initialise the size of the array. But this produces a initialising problem,
variable length array of non-POD element type vector<int>
Anyone knows what I can do to solve this?

You are attempting to define an array of vectors, but arrays cannot have runtime determined sizes. Presumably, you want to declare a vector of a certain type, which you can do like this:
vector<int> graph(number); // vector of size = number
Edit: After your comments, it seems that what you're after is a vector of vectors:
vector<vector<int>> graph(number);

Check this related posts, as they have this same problem as yours:
c++: Error: variable length array of non-POD element type
Variable length array of non-POD element type 'string' (aka 'basic_string<char>') c++

You're trying to create an array of vectors, which is not a good thing if you don't do this through dynamic allocation. If you want an array of vectors, do this:
vector<int> * graph = new vector<int>[number];
...
delete[] graph;
If you want to have a vector of size number, then do this:
vector<int> graph(number);

Related

initialize a vector of vectors of arrays returns an error

i would like to initialize a vector of vectors of arrays like this
vector<vector<int[4]>> gri =
{
{{8,5,9,4},{9,1,5,9},{6,9,6,6}},
{{7,4,6,1},{6,8,3,4},{1,1,9,0}},
{{9,6,0,4},{0,4,8,2},{5,9,1,8}}
};
i'm novice in c++ but i think i'm doing right the error i'm getting is
array must be initialized with a brace-enclosed initialize
i can't identify the issue, despite i'm using brace-enclosed, can anyone tell me what's wrong in my code please.
Use an array:
vector<vector<array<int,4>>>
You can't store int[4] in a vector directly.

error : no match for 'operator[]'

I am solving a problem in which I m trying to pass address a 2-D array of a structure and trying to manipulate it but, whenever I use [] operator to access the array elements , I get a compile time error:
no match for 'operator[]'
in my codeblocks IDE.
#include <iostream>
using namespace std;
typedef struct mat
{
int data;
int flag;
} cell;
int mat(cell *);
int main()
{
int m,n;
cin>>m>>n;
cell game[n][m];
cout<<"The length of matrix is "<<mat(&game[0][0]);
}
int mat(cell *arr)
{
return (sizeof(arr[0])/sizeof(arr[0][0]));
}
cell game[n][m];
This is not legal C++. You are using a compiler-specific extension. At this point I advise you against using any compiler-specific extensions. Use standard C++ only. In standard C++ there are no Variable Length Arrays. Don't use arrays in your C++ programs. To get proper variable length array functionality. You should use std::vector instead, like this:
std::vector<std::vector<cell>> game;
Further,
&game[0][0]
is not an address of a 2D array. This is an address of the first element in the array. It contains no information about the number of elements. It is lost forever. You cannot pass it to some function and expect the size of the array to be recovered. To get proper array functionality with a built-in size function, use std::vector.
Last but not least,
(sizeof(arr[0])/sizeof(arr[0][0]));
arr is a cell*. arr[0] is a cell. arr[0][0] is invalid because a cell is neither an array not a pointer, nor it has a custom [] operator defined. In any case you cannot use sizeof to recover the number of elements in the array from a pointer to its first element. To get proper array functionality with a built-in size function, use std::vector.
Two things:
Your function takes a pointer to cell but since you're treating it like a 2D array, you should probably change your signature to either accept a cell ** arr or a cell arr[m][] where m is the (fixed) size of the array and must be specified. Note that these data structures have fundamentally different representations in memory - they just have the same [][] syntax for accessing elements.
You can't use the sizeof function to determine the length of an array if you pass it as a pointer to an elem. You will need to pass the dimensions along with your array, like this:
int mat(cell **arr, int m, int n);
The definition being given basically says that your class doesn't define the operator [], meaning you can't use the syntax you are trying to use.

Passing a 3-dimensional variable size array by reference in C++

I've been working off of Passing a 2D array to a C++ function , as well as a few other similar articles. However, I'm running into a problem wherein the array I'm creating has two dimensions of variable size.
The initialization looks like:
int** mulePosition;
mulePosition = new int *[boardSize][boardSize][2];
The function looks like:
int moveMule (int boardSize, int ***mulePosition)
And the references look like
moveMule (boardSize, mulePosition)
Boardsize is defined at the beginning of the function, but may change per execution.
The array, properly sized, would be int [boardSize][boardSize][2].
Either use a plain '3-dimensional' array via
int* mulePosition = new int[boardsize*boardsize*2];
and address its elements calculating the offset from the beginning: mulePosition[a][b][c] is mulePosition[boardSize*2*a + 2*b + c],
or use array of arrays of arrays (which would correspond to your int*** declaration) or better (and simpler) vector of vectors of vectors, although the initialization would be a little more complex (you would need to initialize every array/vector).
Either use a std::vector<std::vector<int>> if boardSize is not a const or std::array<std::array<boardSize>, boardSize> (see Multidimensional std::array for how to initialize the std::array).
That being said, it looks like a good idea to hide this in a class Board which provides a nice interface.

Is there any built in method in c++ to findout length of an array?

like array.length in java is there any built in method in c++ to findout size of an array?
I know about length(). but it only works for strings only ...
And i tried this ...
int a[10];
a[0]=1;
a[1]=2;
print(sizeof(a)/size(a[0]))
but it gives output as 10 but is there a way getting only 2 as output
If you're using C++, don't use arrays, use std::vector instead (especially if you need the count of currently held items, not the container's capacity). Then you can write:
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
printf("%d\n", vec.size());
int a[10];
declares an array of 10 ints; sure, you're only initialising the first two, but the other 8 are still there, they're just (probably) filled with junk at the moment.
To do what you want, you should use a std::vector instead. You can then do this:
std::vector<int> a;
a.push_back(1);
a.push_back(2);
std::cout << a.size() << std::endl; // prints 2
Arrays in C/C++ do not store their lengths in memory, so it is impossible to find their size purely given a pointer to an array. Any code using arrays in those languages relies on a constant known size, or a separate variable being passed around that specifies their size.
In an array of 10 ints, when it is declared, memory is allocated for 10 int values. even if you initialize just two, the rest of it contains some junk values and the memory remains allocated.
If you want the used size, your best bet is to use std::vector.
if you want to know the number of elements in an array you can do this
int array[3] = {0, 1, 2};
int arraylength = sizeof(array)/ sizeof(*array);
Sure. It's name is vector::size. It doesn't apply to C-style arrays, only to std::vector. Note that Java's Array class is also not a C-style array.

Convert std::vector to array

I have a library which expects a array and fills it. I would like to use a std::vector instead of using an array. So instead of
int array[256];
object->getArray(array);
I would like to do:
std::vector<int> array;
object->getArray(array);
But I can't find a way to do it. Is there any chance to use std::vector for this?
Thanks for reading!
EDIT:
I want to place an update to this problem:
I was playing around with C++11 and found a better approach. The new solution is to use the function std::vector.data() to get the pointer to the first element.
So we can do the following:
std::vector<int> theVec;
object->getArray(theVec.data()); //theVec.data() will pass the pointer to the first element
If we want to use a vector with a fixed amount of elements we better use the new datatype std::array instead (btw, for this reason the variable name "array", which was used in the question above should not be used anymore!!).
std::array<int, 10> arr; //an array of 10 integer elements
arr.assign(1); //set value '1' for every element
object->getArray(arr.data());
Both code variants will work properly in Visual C++ 2010. Remember: this is C++11 Code so you will need a compiler which supports the features!
The answer below is still valid if you do not use C++11!
Yes:
std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer
Elements in a vector are guaranteed to be contiguous, like an array.