How to fill array in C++? - 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);

Related

Variable-sized object may not be initialized problem in array

When I try to run this simple code, it returns a Variable-sized object may not be initialized error. I have no idea why and how to resolve this problem.
int main()
{
int n=0;
n=1;
int a[n]={}, b[n]={};
return 0;
}
The array lenght must be known at compile time.
Either
int a[1];
or
constexpr int n = 1;
int a[n];
Otherwise you need a dynamic array like the std container std::vector.
You can initialize your array properly with the std::fill_n like:
std::fill_n(a, n, 0);
std::fill_n(b, n, 0);
or use std::vector like:
std::vector<int> a(n);
It will initialize all the elements to 0 by default.
Or, you can have something like:
constexpr size_t n = 10;
int a[n]{};
This will also initialize all the elements to 0.
Try this:
const int n=1;
int main()
{
int a[n]={}, b[n]={};
return 0;
}
The above code will let you create an array with length n.
Note: n can't be changed.

Assigning vector sizes as array lengths

So I am currently working on a program in c++, and I want to make the following decleration:
methodOne()
{
vector<int> one;
vector<int> two;
... assigning to one and two...
int a = one.size();
int b = two.size();
methodTwo(a, b);
}
methodTwo(int a, int b)
{
int array[a][b];
}
When I attempt this, I get an error: a and b must be constant
I have tried to assign a and b to const int a, const int b. However, that was no help. I was wondering if anyone knows how I can fix this kind of error. Thanks in advance for any help you are able to give!
An array's size must be known before the program runs. Its size is part its complete type, just like the element type itself.
You need something with a dynamic size instead. Use a std::vector<int> of size a * b:
methodTwo(int a, int b)
{
std::vector<int> array(a * b);
}
You could also use a std::vector<std::vector<int>> instead, but why take all the trouble? After all, you can access the one-dimensional vector's elements as if it was two-dimensional data structure by calculating the offsets accordingly:
methodTwo(int a, int b)
{
std::vector<int> array(a * b);
// ...
int x = 5;
int y = 6;
auto const element = array[y * a + x];
}
I see you already using vector so you can replace your array with
typedef std::vector< std::vector<int> > matrix;
matrix name(a, std::vector<int>(b));

2D Array Value Assign After Declaration in 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.

Accessing an entire row of a multidimensional array in C++

How would one access an entire row of a multidimensional array?
For example:
int logic[4][9] = {
{0,1,8,8,8,8,8,1,1},
{1,0,1,1,8,8,8,1,1},
{8,1,0,1,8,8,8,8,1},
{8,1,1,0,1,1,8,8,1}
};
// I want everything in row 2. So I try...
int temp[9] = logic[2];
My attempt throws the error:
array initialization needs curly braces
I know I can retrieve the row using a FOR loop, however I'm curious if there was a more obvious solution.
That's not how arrays/pointers work in C++.
That array is stored somewhere in memory. In order to reference the same data, you'll want a pointer that points to the the beginning of the array:
int* temp = logic[2];
Or if you need a copy of that array, you'll have to allocate more space.
Statically:
int temp[9];
for (int i = 0; i < 9; i++) {
temp[i] = logic[2][i];
}
Dynamically:
// allocate
int* temp = new int(9);
for (int i = 0; i < 9; i++) {
temp[i] = logic[2][i];
}
// when you're done with it, deallocate
delete [] temp;
Or since you're using C++, if you want to not worry about all this memory stuff and pointers, then you should use std::vector<int> for dynamically sized arrays and std::array<int> for statically sized arrays.
#include <array>
using namespace std;
array<array<int, 9>, 4> logic = {
{0,1,8,8,8,8,8,1,1},
{1,0,1,1,8,8,8,1,1},
{8,1,0,1,8,8,8,8,1},
{8,1,1,0,1,1,8,8,1}
}};
array<int, 9> temp = logic[2];
As well as decaying the array to a pointer, you can also bind it to a reference:
int (&temp)[9] = logic[2];
One advantage of this is it will allow you to use it C++11 range-based for loops:
for (auto t : temp) {
// stuff
}
A direct assignment won't work. C++ does not allow that. At best you'll be able to assign them to point to the same data - int *temp = logic[2]. You'll need a for loop or something like the below.
I believe this would work:
int temp[9];
memcpy(temp, logic[2], sizeof(temp));
But I'd generally suggest using std::vector or std::array instead.

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.