I am mis-understanding something about the code below. From my understanding the tester declaration should return a pointer to the first array of two elements, i.e. [1,2], and so *(tester+1) should return [3,4], which only has 2 elements so how does it make sense to call (*(tester + 1))[2] . This example prints the number 5 by the way. Any clarifications much appreciated.
int main() {
int tester[][2]{ 1,2,3,4,5,6 };
cout << (*(tester + 1))[2] << endl;
return 0;
}
When you declare a 2-dimensional array, all the elements are contiguous. The entire array is a single object, so you're not going out of bounds when you just exceed one of the row limits, so longer as you're still in the array. So the next element after tester[1,1] is tester[2,0], and that's what (*(tester + 1))[2] accesses.
[2] is higher than the highest element at [1] because the index starts at [0]
There are three arrays.
[1,2] positions 0,0 and 0,1
[3,4] positions 1,0 and 1,2
[5,6] positions 2,0 and 2,1
Since all of the arrays are next to each other in the data segment, going out of bounds on the second array (tester + 1) bleeds over into the third array giving you the first element of the third array.
i.e. position 1,2 is the same as 2,0
int tester[][2]{ 1,2,3,4,5,6 } creates a 3 by 2 array.
tester[0][0] = 1
tester[0][1] = 2
tester[1][0] = 3
tester[1][1] = 4
tester[2][0] = 5
tester[2][1] = 6
The compiler creates an array using the least amount of memory possible based on your specifications. [][2] explicit says to organize the data in such a fashion that there a x rows and 2 columns. Because you put 6 elements into the tester array, the compiler decides the number of rows to assign by dividing the number of total elements by the number of columns.
Furthermore, (*(tester + 1))[2], is equivalent to tester[2], which would access the element in the first column of the third row. Thus returning 5.
It is another way to write this code which means you define vector but it acts like 2-dimensional array.
int main() {
int tester[3][2]{ {1,2},{3,4},{5,6} };
std::cout<< tester[1][2] <<std::endl;
return 0;
}
Related
C++: vector<pair<int,int>>v(size); showing 0 as values when I am trying to print out the values, but when the vector size is not declared it is showing correct output? Why so?
For example:
int x;
cin>>x;
vector<pair<int,int>>v(x); //Size declared.
for(int i=0;i<x;i++){
int p,q;
cin>>p>>q;
v.push_back(make_pair(p,q));
}
But when I am trying to print the values, it is printing 0 only.
I/P->
3
1 2
3 4
5 6
O/P->
0 0
0 0
0 0
But when I don't declare the size of the vector it prints the output without any error, why is that?
i.e
int x;
cin>>x;
vector<pair<int,int>>v; //Size is not declared.
for(int i=0;i<x;i++){
int p,q;
cin>>p>>q;
v.push_back(make_pair(p,q));
}
I/P->
3
1 2
3 4
5 6
O/P->
1 2
3 4
5 6
It shows the correct output. Why is that?
It is because the vector's constructor accepting an integral (it is of type size_t) does not only provide sufficient size, but creates x default objects. You then append your new objects to these default ones.
Be aware that the term 'size' in STL wording refers to the number of elements already inserted/contained, the total number of elements that can be held without re-allocation is referred to as 'capacity'.
If you want to pre-allocate sufficent capacity without creating new objects, you need to use reserve:
std::vector<std::pair<int,int>> v;
v.reserve(x);
Vector constructor with int means it create that many elements. They are pairs of zeroes. Then you push back and it creates new elements at the end. So all elements are X * 2.
I am assuming then you do not check the size, but instead you list first X elements.
You can fix by either vector::reserve(x) or by using []instead of pushing back. Then operation will look more like array access.
Because element is pair of int, both options are good.
Reserve is faster, array like access is more generic.
Difference From Other Questions
I am not asking how to find the size, but how the computer finds the size.
Goal
I want to find out how C++ finds the size of an array (using sizeof(array)), and a 2D array (using sizeof(array)).
When I ran the code, I thought the output would be 3 and 6. But it was 12 and 24!? How do I make the the output 3 and 6?
I don't know how to calculate the size of an array, so when I say "an output of three/six", I mean the amount of numbers in the array.
Code
#include <iostream>
using namespace std;
int main()
{
int oneDArray [3] = {1, 2, 3};
int twoDArray [2][3] = {{1, 2, 3}, {1, 2, 3}};
cout << sizeof(oneDArray) << "\n" << sizeof(twoDArray);
return 0;
}
The sizeof operator returns the size in bytes, not elements.
For single dimensional arrays (not passed as a function argument, which would cause decay to a pointer), you can get the element count by dividing the size of the array by the size of the first element, e.g.
sizeof(oneDArray) / sizeof(oneDArray[0]) // Gets 3
For multidimensional arrays, that would tell you the size of the first dimension, not the number of elements total, so you'd need to drill down deeper:
sizeof(twoDArray) / sizeof(twoDArray[0]) // Gets 2 (first dimension of array)
sizeof(twoDArray) / sizeof(twoDArray[0][0]) // Gets 6 (number of elements)
You can of course explicitly name the type of an element to avoid nested indexing (sizeof(twoDArray) / sizeof(int) get 6 just fine), but I avoid it as a rule; it's too common for an array to change types during development (say, it turns out you need to use int64_t because you have values into the trillions), and if the whole expression isn't in terms of the array, it's easy to overlook it and end up with broken code.
sizeof returns bytes, if you expect number of elements, divide by the size of each element
cout << sizeof(oneDArray)/sizeof(int) << "\n" << sizeof(twoDArray)/sizeof(int);
Output:
3
6
I have two arrays, one sorted array int b[] and other unsorted array int a[n] having n elements . The sorted array is made of some or all elements of unsorted array. Now there are M queries. For each query values of l and r are given. In each query I need to find the number of elements of a[n] which are present in b[].
For eg -
N=5 ,M=2
a= [2 5 1 2 3]
b=[3 2 1]
for each m:
l=1 r=5 ->a[1]=1, a[5]=5 -> answer should be 3 as all elements of b i.e 1,2,3 are present in a
l=2 r=4 ->a[2]=5 , a[4]=2 ->answer should be 2 as only 1 and 2 are there in b for given value of l and r for array.
How to find the answer with not more than O(M * LOGN) time complexity ?
NOTE:
Array is not necessary. Vector can also be used that is if it helps in reducing time complexity or easier to implement the code.
Well i think you can do something like this
std::map<int,int> c;
for(int i = 0;i<b.length.i++){
c[b[i]] = 0;
}
for(int i = l; i<=r; i++){
int number = a[i];
c[number]++;
}
//Iterate through c with b index and get all number which different than 0. The left is for you
The purpose of this is creating a map hold index of B. Then while iterating A you can increase the c value. So that after that you can check whether each element in C has value different than zero mean that A has hold the number of B.
You can use array instead of map if C starting from zero and increase by 1 for better performance. Make sure to check if a[i] can throw out of bounds exception if you use array.
#include<iostream>
#include<iomanip>
void main()
{
int i,j;
int pole[3][3]={1,2,3,4,5,6,7,8,9};
*(*(pole+2)+2)=0;
for(i=0; i<3;i++)
{
for(j=0;j<3;j++)
{
cout << setw(5)<< pole[i][j];
}
cout << endl;
}
}
This is my program and the output I get is the following:
1 2 3
4 5 6
7 8 0
However, I have troubles understanding what exactly does this line mean:
*(*(pole+2)+2)=0;
In my understanding, it's a pointer to pointer of array, so basically, the first we do:
*(pole+2)
which points to the 2nd element of the array. Then
*(*(pole+2)+2)
which points to the 4th element of the array? Is this correct? If so, how do we change the last [3][3] element to 0?
Thank you.
Here pole is a 2D array of 3 rows and 3 columns. So as array index starts from 0, you are assigning pole[2][2] = 0 which actually means 0 is assigned to 3rd row and 3rd column element.
*(*(pole+2)+2) == *(pole[2] + 2) == pole[2][2]
I just learned about pointers in and arrays in depth in my C++ so i hope i can help
you declared a 2D Array which is really just an array of an array of int types.
(pole + 2) points to pole's base address and adds 2(size of an array of ints) to it so:
2*int(4 bytes) * 3(size of array) = 24 bytes
so it adds 24 bytes to the address. it is now pointing to the 3rd array. then it takes that and points to:
3rd arrays base address + 2*int(4bytes)
which will lead it to the 3rd index of that array which is 9. It then changes this value to 0.
the key is that the first pointer is pointing to an Array of arrays. the second pointer points to the index inside of that array.
I hope i didn't confuse you.
I've came across a problem when coding with C++ 2D array.
Just a little question, what does the code below mean?
...
if(array[x][y] >= 9){
...
}
...
Does that mean when the sum of x and y of the array is greater or equal to 9, then only the body of the IF will run? Or ........?
Please explain and provide some simply examples.
the array is two dimensional, it means the element at array[x][y]
unlike 1D arrays, which only require 1 index, 2D arrays require 2 indices in the form of array[x][y] presumably in a nested for loop.
You can iterate through such an array like this
for (int x = 0; x < arrayLength; x++) {
for (int y = 0; y < array[x]Length; y++) {
// do something with array[x][y]
}
}
where arrayLength is the length of array and array[x] length is the length of array[x].
So in reference to the code that you posted, it's testing to see if the member of the 2D array is greater than or equal to 9.
Ok let's start with the basics.
1D Arrays
How can you imagine a normal array? You could say a normal array is like a number line:
|-------------------------------| where every - is one element in your array
The very first '-' on the left side is the element at myArray[0] (the '|' are just symbolizing that it has a start and a end).
2D Arrays
A 2D array can be visualized as checkerboard, bookshelf or a table with columns and rows.
|-------------------------------|
|-------------------------------|
|-------------------------------|
|-------------------------------|
Just like in chess you need 2 values in order to address an element. If you only specify one value the compiler might know the row of your value but not its column (or the other way around). That means you need x and y coordinates (which is a visual analogy for a coordinate system). In order to address a value you have to do it like this:
myArray[x][y] where x could be the row of our checkerboard and y the column.
In your case your 2D array is most likely filled with integers. The 'if' statement checks if the value stored in myArray[x][y] is larger than 9. If myArray[x][y] is larger than 9 this statement returns true and the code inside will get executed.
After executing the code inside of the 'if' statement the program will continue to execute the code after the if statement. 2D arrays can be understood as an array containing arrays.
If you are thinking 3 dimensional arrays are possible you're right. Here you need 3 coordinates in order to describe a point since you have depth, height and length (here I'm talking about the visual length not the length in terms of total amount of elements.).
I don't know whether this helped but this is of course a very visual approach of explaining how multi-dimensional arrays work.
Example
int myArray[3][3] = {{1, 2, 3}, // row 0
{4, 5, 6}, // row 1
{7, 8, 10}}; // row 2
In this case your if statement would only be executed if x = 2 and y = 2 since myArray[2][2] = 10
It means "IF the element at coordinates (x,y) is greater or equal than 9...".
There is no addition operation. The array is probably declared with the minimum dimensions (x+1, y+1).
int array[2][2] = {{12, 6}, {3, -2}};
int x=1, y=0;
if(array[x][y] >= 9){...} // array[1][0] equals 3, condition is false