Initialize new c++ array with different specified values - c++

I am able to initialize an array with default values
int arrayWithDefault[5] = { 0 };
Also able to initialize new array with default values
int *ptrArrayWithDefault = new int[2]();
How can i initialize a new array with different values such that
ptrArrayWithDefault[0] == 1 && ptrArrayWithDefault[1] == 2
I can simply solve it with
int arrayWithDefault[] = { 1, 2, 3, 4 };
but i was wondering if there is a way to initialize new array in such way?

I would really avoid such a scenario and follow proper practices.
However, I was able to do similar task using
int *ptr = new int[]{1, 2, 3, 4, 5};
and with this way
ptr[0] = 1
.
.
.
ptr[4] = 5

Related

which is best way to initialize array, "memset" or " {//value} "?

int main(){
int ar[50]={1};
//OR
int br[50];
memset(br, 1, sizeof(br));
return 0;
}
int ar[50]={1};
This will set only the first element to 1. Rest all will be 0.
memset(br, 1, sizeof(br));
This will set all the bytes in br to 1. It is not the same as setting all the values to 1. The values afterwards are:
{16843009, 16843009, 16843009, 16843009, 16843009}
Use memset when you know you really need it. It is not exactly made for initializing arrays, it just set the memory to a particular value.
Best way in C++? Use std::fill or std::fill_n.
Example:
int array[5];
std::fill(array, array + 5, 8);
Array now contains:
{8, 8, 8, 8, 8}
Using fill_n
std::fill_n(array, 5, 99);
Array now contains:
{99, 99, 99, 99, 99}
As a side note, prefer using std::array instead of c-style arrays.
Try on godbolt: https://godbolt.org/z/DmgTGE
References:
[1] : Array Initialization
[2] : memset doc
suppose you do
int ar[50] = {-1};
Now you will expect this line to initialize all array elements with -1
but it will not. It will only set the first element of array to -1 and rest to 0.
Whereas memset will show the expected behaviour.
See this Initialization of all elements of an array to one default value in C++? for more info.
let's take an example:-
int arr[5] = { 1, 2 }; // this will initialize to 1,2,0,0,0
int ar[5] = { }; // this will initialize all elements 0
int myArray[10] = {}; // his will also all elements 0 in C++ not in c
So If you want to initialize a specific value to an array use memset().
If you want to initialize all elements in an array to 0 use
static int myArray[10]; // all elements 0
Because objects with static storage duration will initialize to 0 if no initializer is specified and it is more portable than memset().
Also, The int ar[50]={0}; will be infinite because it just initializes the array and does not have an ending but in memset(arr,0,sizeof(br)) it has the correct way of ending the loop in arrays

How to generate knock-out vectors in Chapel?

I have a matrix, yes, A. Operating on her rows, I often need to create "knock-out" vectors. Basically
var v = [5, 4, 3, 2, 1];
v_{-2} = [5, 3, 2, 1]; // e.g. v[2] is removed
I don't want to remove it permanently, just for this calculation, and I want to do it along the rows of A.
var knockouts: [A.dim(1)] int; // list of knockout dims, as tall as A
for i in A.dim(1) {
var w = ||v_{-knockouts[i]}|| / ||v||
}
== UPDATE ==
More on A to keep it general. It is very large and (as is my wont) sparse. The elements knocked out are expected to be within the populated subdomain, but may not be in some cases. The entries are often probabilities, as in a stochastic matrix, so a few common row operations are
r = A[i,..]
s = r[3] / sum(r_{-3})
s = sum(r[3] log(r_{-3}))
s = sum(log (r_{-3})) / sum (log (r_{-5}))
With all the logging going on, it may not be safe to set r[3] = 0. But if that is the solution, it would still be nice to have a convenience function to do it under the covers. I don't recall seeing one but, maybe sum(r.except(3)) or another syntax.
I don't know of a good way to do this "in-place" such that no temporary arrays
are created.
For now, here's an approach that knocks out indices by creating a temporary array:
var v = [5, 4, 3, 2, 1];
writeln(exclude(v, 2)); // 5 3 2 1
writeln(exclude(v, 3)); // 5 4 2 1
/* Returns array with element at idx excluded */
proc exclude(A: [], idx) {
var v1 = A[..idx-1];
v1.push_back(A[idx+1..]); // See NOTE
return v1;
}
NOTE: Passing arrays to push_back() is not supported in Chapel 1.15. It has been added in
#7180.

Bijective mapping of integers

English is not my native language: sorry for my mistakes. Thank you in advance for your answers.
I'm learning C++ and I'm trying to check to what extent two sets with the same number of integers--in whatever order--are bijective.
Example :
int ArrayA [4] = { 0, 0, 3, 4 };
int ArrayB [4] = { 4, 0, 0, 3 };
ArrayA and ArrayB are bijective.
My implementation is naive.
int i, x=0;
std::sort(std::begin(ArrayA), std::end(ArrayA));
std::sort(std::begin(ArrayB), std::end(ArrayB));
for (i=0; i<4; i++) if (ArrayA[i]!=ArrayB[i]) x++;
If x == 0, then the two sets are bijective. Easy.
My problem is the following: I would like to count the number of bijections between the sets, and not only the whole property of the relationship between ArrayA and ArrayB.
Example :
int ArrayA [4] = { 0, 0, 0, 1 }
int ArrayB [4] = { 3, 1, 3, 0 }
Are the sets bijective as a whole? No. But there are 2 bijections (0 and 0, 1 and 1).
With my code, the output would be 1 bijection. Indeed, if we sort the arrays, we get:
ArrayA = 0, 0, 0, 1;
ArrayB = 0, 1, 3, 3.
A side-by-side comparaison shows only a bijection between 0 and 0.
Then, my question is:
Do you know a method to map elements between two equally-sized sets and count the number of bijections, whatever the order of the integers?
Solved!
The answer given by Ivaylo Strandjev works:
Sort the sets,
Use the std::set_intersection function,
Profit.
You need to count the number of elements that are contained in both sets. This is called set intersection and it can be done with a standard function - set_intersection, part of the header algorithm. Keep in mind you still need to sort the two arrays first.

How to set every element in an array to 0

I am learning C++ and one of my practice exercises is to use pointers to set all the elements in an array to 0. I have no idea how to do this by incrementing the pointer to the next position in the array since my IDE log said that comparison between int and * is forbidden. I only need a small snippet as an example to help me better understand where i'm going wrong. The array I have created is of type int and has a single dimension with 5 elements consisting of 1,2,3,4 and 5.
int array[5] = {1, 2, 3, 4, 5};
for(int *i = &array[0], *end = &array[5]; i != end; i++)
*i = 0;
The code creates a pointer to the start &array[0] and a pointer to one position past the end &array[5]
Then it steps the pointer through the array, setting each element to zero.
A more advanced concept that is very similar is iterators.
You could use std::fill, http://en.cppreference.com/w/cpp/algorithm/fill, as follows.
const size_t dataSize = 10;
int data[dataSize];
std::fill(data, data + dataSize, 0);

What is the meaning of new int[25,2]?

What is the meaning of using the second parameter with a comma in the below code?
int *num = new int[25,2];
That's the comma operator in action: it evaluates it's operand and returns the last one, in your case 2.
So that is equivalent with:
int *num = new int[2];
It's probably safe to say that the 25,2 part was not what was intended, unless it's a trick question.
Edit: thank you Didier Trosset.
That's the comma operator in action: it evaluates it's operand and returns the last one, in your case 2. So that is equivalent with:
int *num = new int[2];
You are using the comma operator, which is making the code do something that you might not expect at a first glance.
The comma operator evaluates the LHS operand then evaluates and returns the RHS operand. So in the case of 25, 2 it will evaluate 25 (doing nothing) then evaluate and return 2, so that line of code is equivalent to:
int *num = new int[2];
// Declare a single-dimensional array
int[] array1 = new int[5];
// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };
// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// Declare a array
int[][] Array = new int[6][];
// Set the values of the first array in the array structure
Array[0] = new int[4] { 1, 2, 3, 4 };