2D Array Value Assign After Declaration in C++ - c++

I know when we want to assign values to 2D arrays as we declare the array, we do this:
int myArray[2][4] = {{1,2,3,4},{5,6,7,8}};
But how should I assign values "after" declaring it? I want to do something like this:
int myArray[2][4];
myArray = {{1,2,3,4},{5,6,7,8}};
When I do it, the compiler gives error. Help please.

If you want to use std::vector then you can do this:
#include <vector>
int main()
{
std::vector< std::vector<int> > arrV ;
arrV = { {1,2,3,4}, {5,6,7,8} };
}
or using std::array:
#include <array>
int main()
{
std::array<std::array<int,4>,2> arr ;
arr = {{ {{1,2,3,4 }}, {{5,6,7,8}} }} ;
}
Note, the double set of braces in both the inner and outer set. This answer though only works in C++11.

Related

How to retrieve an array from a pointer in c++

I'm having problems with a program that only accepts arrays. I'm having plenty of pointers to different arrays, but using *p seems to only give me the first element of the array. I want to return all the elements of the array. I know the length of the array, if that helps.
#include <typeinfo>
#include <iostream>
int i[10];
int* k=i;
cout<<typeid(i).name()<<'\n';
cout<<typeid(*k).name()<<'\n';
results in 'int [10]' and 'int' respectively. I want some way of returning k as 'int [10]'.
Your k is a pointer to int. It points to the first element of the array. If you want a pointer to the whole array then you need to declare it as such.
#include <typeinfo>
#include <iostream>
int main() {
int i[10];
int* k=i;
int(*p)[10] = &i;
std::cout<<typeid(i).name()<<'\n';
std::cout<<typeid(*k).name()<<'\n';
std::cout<<typeid(*p).name()<<'\n';
}
Output:
A10_i
i
A10_i
However, as others have said, std::array is much less confusing to work with. It can do (almost) anything a c-array can do without its quirks.
Certainly there is a solution to your actual problem that does not require to get the array from a pointer to a single integer.
Example to show you how much more convenient C++ array/vector is then "C" style arrays with pointers :
#include <vector>
#include <iostream>
// with std::vector you can return arrays
// without having to think about pointers and/or new
// and your called cannot forget to call delete
std::vector<int> make_array()
{
std::vector<int> values{ 1,2,3,4,5,6 };
return values;
}
// pass by reference if you want to modify values in a function
void add_value(std::vector<int>& values, int value)
{
values.push_back(value);
}
// pass by const refence if you only need to use the values
// and the array content should not be modified.
void print(const std::vector<int>& values)
{
// use range based for loops if you can they will not go out of bounds.
for (const int value : values)
{
std::cout << value << " ";
}
}
int main()
{
auto values = make_array();
add_value(values, 1);
print(values);
std::cout << "\n";
std::cout << values.size(); // and a vector keeps track of its own size.
return 0;
}

Passing an array in struct initialization

I would like to create a struct which contains both an int and an array of int. So I define it like
struct my_struct {
int N ;
int arr[30] ;
int arr[30][30] ;
}
Then I would like to initialize it with an array which I have already defined and initialized, for example
int my_arr[30] ;
for (int i = 0; i < 30; ++i)
{
my_arr[i] = i ;
}
Then I thought I could initialize a struct as
my_struct A = {30,my_arr}
but it doesn't seem to work (gives conversion error).
P.s. and how would it work with a 2d array?
Arrays cannot be copy-initialised. This isn't particular to the array being member of a class; same can be reproduced like this:
int a[30] = {};
int b[30] = a; // ill-formed
You can initialise array elements like this:
my_struct A = {30, {my_arr[0], my_arr[1], my_arr[2], //...
But that's not always very convenient. Alternatively, you can assign the array values using a loop like you did initially. You don't have to write the loop either, there's a standard algorithm for this called std::copy.

How to fill array in C++?

#include <iostream>
#include <array>
using namespace std;
int main(){
int a = [];
int b = 10;
std::fill(a);
cout<<a<<endl;
}
I have an array "a" and want to fill it with an integer "b". As I remember in python its simply uses apppend, does someone know solution?
Here one solution how to use your array header.
int b = 10;
std::array<int, 3> a;
std::fill(begin(a), end(a), b);
I have an array "a"
int a = [];
What you have is a syntax error.
As I remember in python its simply uses apppend
A major difference between a C++ array and python list is that the size of C++ array cannot change, and thus nothing can be appended into it.
How to fill array in C++?
There is indeed a standard algorithm for this purpose:
int a[4];
int b = 10;
std::fill_n(a, std::size(a), b);
Decide the size for a, as it is an array not a list. For example:
int a[10];
Then use index values to fill in the array like:
a[0] = 1;
a[1] = 4;
etc.
If you want a dynamic array use std::vector instead
Here is how its done with vectors:
std::vector<int> myvector;
int myint = 3;
myvector.push_back (myint);
Following zohaib's answer:
If your array is of fixed length:
You can use the array's 'fill' member function like this:
a.fill(b);
If your array can change it's size you can use the std's fill function like this:
std::fill(a.begin(), a.end(), b);

Structure that contains vectors with different sizes, cpp

I wish to declare a structure, say with size n=10, that in each i site of the structure there is a vector. The vectors in the sites of the structure have different sizes.
In matlab it can be obtained using struct. how it is done in C++?
I think what you are looking for is an array, or a vector, of vectors.
For example:
#include <array>
#include <vector>
#include <iostream>
int main ()
{
std::array<std::vector<int>, 10> Vectors;
for (auto &i : Vectors) //Loop through all 10 vectors in Vectors
{
for (int j=0; j<5; j++) //Push 1, 2, 3, 4, and 5 into each vector
{
i.push_back(j);
}
}
return 0;
}
struct S {
std::array<std::vector<int>, 10> data;
};
You can also use an alias as well:
using arrayOfTenVectors = std::array<std::vector<int>, 10>;
Of course int is a placeholder. You can make either the struct or the alias a template and use some T inside of the vector.

Array Initialization from a struct

I was wondering if there was a way to initialize an array out of a variable from a struct. Say you have a struct like this-
struct Test{
int Number;
};
And you wanted to initialize the int Number to become an array.
I've already tried this, and it doesn't work:
Test t1;
t1.Number = new int[3];
t1.Number[3] = 6;
I know ISO C++ forbids resizing arrays, but if there was a way to initialize the integer to be an array, that's not really resizing(isn't it?)
Also, vectors don't work inside of structs. I get a "Vector does not name a type" error.
P.S., I can't do this either:
struct Test{
int Number[5];
};
Because at that time I don't know the size of the array I want.
vector works just fine in structs:
#include <vector>
struct Test {
std::vector<int> Numbers;
};
I'm not sure what you're really trying to do but I think this comes close.
One trick to do this
struct Test {
int Numbers[1];
};
when you initialize the struct, you need to use your own allocation function.
struct Test *NewTest(int sizeOfNumbers) {
return (struct Test*)malloc(sizeof(struct Test) + sizeof(int)*(sizeOfNumbers - 1));
}
then, you will be able to access the numbers by using,
struct Test *test1 = NewTest(10);
test1->Numbers[0]...
test1->Numbers[1]...
test1->Numbers[9]...
The return value of new int[3] is an int* not an int. To make your code work you can do:
struct Test {
int* Number;
};
int main() {
Test t1;
t1.Number = new int[4]; // Note this should be 4 so that index 3 isn't out of bounds
t1.Number[3] = 6;
delete t1.Number;
return 0;
}
However you should really use a std::vector rather than a static array. Vectors work just fine inside structs:
#include <vector>
struct Test {
std::vector<int> Number;
};
int main() {
Test t1;
t1.Number.resize(4);
t1.Number[3] = 6;
return 0;
}
You can use a pointer to int -- i.e.,
struct Test{
int *Number;
};
Then you can assign this at any future time to point to an array of your preferred size:
t.Number = new int[5];
But as other posters have already said, std::vector, with a small "v", works fine; be sure to #include <vector> so the compiler knows what you're talking about.