Printing vector of pair in C++ - vector

Here is the code to print the value in vector of pair
But why does it print the output mentioned below..?
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<pair<int,int>>vec(3,pair<int,int>()); // declaring the vector of pair.
for(auto x: vec)
x=make_pair(1,2); // looping through it to insert values
for(auto x:vec)
cout<<x.first<<" "<<x.second<<endl; // printing it
return 0;
}
Output :
0 0
0 0
0 0
Expected :
1 2
1 2
1 2

In your first for-loop you iterate through your vector "by value", meaning you copy the elements to auto x and afterwards set x to {1,2}, this does not change your original vector. To actually change your vector you have to iterate through it by reference:
for(auto& x: vec)
x=make_pair(1,2);

Related

Recursion and return of a index of array using recursion

can someone explain how variable ans return the index of an array if my array is 9 8 10 8 and I want to search 10 and in recursion ans will return 1 and then it will ad with ans+1 and return 2.
enter code here
int firstIndex(int input[], int size, int x)
{
if(size==0)
{
return -1;
}
if(input[0]==x)
{
return 0;
}
int ans=firstIndex( input+1, size-1, x);
if(ans!=-1)
{
return ans+1;
}
else
{
return ans;
}
}
Ok, so the function when it receive the first call, the vector looks like this:
[9 8 10 8]. Then it compares 9 with 10 (the element in search). Since they are not equals, the function makes a recursive call, but with a new vector, [8 10 8]. in that moment we have in our stack the first call. Let's call it C1.
Then it compares 8 with 10 (the element in search). Since they are not equals, the function makes a recursive call, but with a new vector, [10 8]. in that moment we have in our stack the second and first call. Let's call it C2 C1.
Then it compares 10 with 10 (the element in search). Since they are equals, the function makes returns 0. So in our stack, the C2 function receive a 0 as a result. Since it is different to -1, then it returns 1 to the C1 call. Since 1 is not equal to -1, it returns 2 leaving the correct result.

Go: pop from a map

Is there an existing function where we can pop a (key,value) pair from a map in GO? I use the word pop instead of remove because a pop would re-arrange the elements after the index where the (key,value) was removed.
As an example the following code:
package main
import "fmt"
func main() {
mapp := make(map[int]int)
fmt.Println("before removal:")
for i := 1; i < 7; i++ {
mapp[i] = i
}
fmt.Println(mapp)
delete(mapp, 2)
fmt.Println("\nafter the removal:")
for i := 1; i < 7; i++ {
fmt.Println(i, mapp[i])
}
}
Produces the following output:
before removal:
map[1:1 2:2 3:3 4:4 5:5 6:6]
after the removal:
1 1
2 0
3 3
4 4
5 5
6 6
We notice that index location 2 is empty. I would like the output to be the following:
before removal:
map[1:1 2:2 3:3 4:4 5:5 6:6]
after the removal:
1 1
2 3
3 4
4 5
5 6
Is this functionality already in Go or would I have to implement it?
I think that you are misunderstanding what a map is and how it works. You should not see it as an "array with gaps", but as a classic hash table.
And to answer your question, when you use delete(), the value is deleted from the map, the problem is how you iterate over the "values" of the map.
To help you understand:
mapp := make(map[int]int)
fmt.Println(2, mapp[2])
will print
2 0
Why ? Simply because when the requested key doesn't exist, we get the value type's zero value. In this case the value type is int, so the zero value is 0.
So, you want to see if a key exists in the map before printing it and you have to use two-value assignment, like that:
for i := 1; i < 7; i++ {
if value, exists := mapp[i]; exists {
fmt.Println(i, value)
}
}
and it will print
1 1
3 3
4 4
5 5
6 6
Not really what you want, but the closer you can get directly with maps.
You can have a look at this blog post for more information and examples.
If you really want to have an array where you can remove values, see Verran's answer and use slices instead.
From the Go documentation:
When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next.
From this, it follows that there would be no way to automatically move a value up one position to fill a gap, since the key can be in a different iteration position each time you look at the values and theres no guarantee that the value mapped to 2 will slide up to 1.
If you want to do something like this, you will have to manually shift everything down one key value, something like:
for key := 2; key < len(map)-1; key++ {
map[key] = map[key+1]
}
Alternatively, you could use slices and if you know the index you need to "pop", create a new slice that omits the value:
value := slice[2]
slice = copy(slice[:2], slice[2+1:])

Xtend and Arrays

Does xtend support two-or more dimensional arrays? If yes: How can i create one and use it later on? I want to store Strings in these arrays and pass it to the files.
Here is my solution that creates a matrix of integers (rows x cols).
The only disadvantage is that each row is allocated separately in a loop.
#Pure
static def int[][] newIntArrayOfSize(int nrow, int ncol) {
newArrayOfSize(nrow).map[ newIntArrayOfSize(ncol) ]
}
Demo:
// allocate 3 rows by 2 columns
val m = newIntArrayOfSize(3, 2)
// notice that indexes are starting from 0
// here setting value 5 on row=2, col=1
m.get(2).set(1, 5)
for(row : 0 .. 2) {
for(col : 0..1) {
print(m.get(row).get(col))
print("\t")
}
println()
}
Easy, just import the Guava lib into your XTend script. The Guava lib has multidimenional MultiSet in it.

Cannot index 2D array with (attempt to index field '?' (a nil value) )

I have 2 different 2d Arrays set up in lua. The first loop
bubbleMat = {} --Set Up Table called bubbleMat
for i = 1, 10 do
bubbleMat[i] = {} --1D table with 10 components
for j = 1, 13 do
bubbleMat[i][j] = bubbleClass.new( (i*62) - 62, (j*62) - 62 ) --2D Table with 10x13 Matrix each cell given a coordinate as it is iterated through the loop
end
end
With this array i can print value of any position in the array to the console with
print(bubbleMat[x][y])
for whatever numbers of x and y
The second array for some reason does not work. The second array is as follows
bubbleMat = {} --Set Up Table called bubbleMat
for j = 1, 13 do
for i = 1, 10 do
bubbleMat[i] = {}
--bubbleMat[i][j] = {}
if j%2 == 0 then
bubbleMat[i][j] = bubbleClass.new( (i*62) - 31, (j*62) - 62 )
else
bubbleMat[i][j] = bubbleClass.new( (i*62) - 62, (j*62) - 62 )
end
end
end
print(bubbleMat)
I am unsure why I cannot index the second array
this is the following error I get in the console
attempt to index field '?' (a nil value)
Thanks in advance for any help.
Basically i want to display a grid of bubbles stored in a 2d array in the following pattern
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
as opposed to having the bubbles in the next line positioned directly underneath
Loop for j is outside and loop for i is inside. This is not necessarily false, but unusual.
However, bubbleMat[i] is initialized to {} in the innermost loop, which is clearly wrong.
Either move that initialization into the outermost loop, or use this syntax :
bubbleMat[i] = bubbleMat[i] or {}

Why doesn't this "binding" code work as expected in JavaFX?

I am new to JavaFX. I am not able to understand why the code below doesn't work.
import javafx.util.Sequences;
def nums = [1..10];
var curr = 0;
var evenOrOdd = bind if (nums[curr] mod 2 == 0) "{nums[curr]} is an even number" else "{nums[curr]} is an odd number";
for (curr in [0..(sizeof nums -1)])
{
println("{evenOrOdd}");
}
I am getting
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
If I change the code to
import javafx.util.Sequences;
def nums = [1..10];
var curr = 0;
var evenOrOdd = bind if (nums[curr] mod 2 == 0) "{nums[curr]} is an even number" else "{nums[curr]} is an odd number";
for (i in [0..(sizeof nums -1)])
{
curr = i;
println("{evenOrOdd}");
}
I get the correct output:
1 is an odd number
2 is an even number
3 is an odd number
4 is an even number
5 is an odd number
6 is an even number
7 is an odd number
8 is an even number
9 is an odd number
10 is an even number
Clearly, the counter increment in the loop is not treated as a value change and the bound expression is not re evaluated.
Can anyone please explain the concept behind this behavior?
The for expression implicitly defines its iteration variable (that's why you didn't need to declare i in your second example). Even if there is already a variable with the same name, for will still create a new one for its scope. Your bind expression is bound to the curr variable outside of your for loop, not to the one inside your for loop. And the one outside of your loop doesn't change, so the bound expression will not change.
Example to demonstrate this behaviour of for:
var curr = 0;
var ousideCurrRef = bind curr;
println("Before 'for' loop: curr={curr}");
for (curr in [0..3])
{
println("In 'for' loop: curr={curr} ousideCurrRef={ousideCurrRef}");
}
println("After 'for' loop: curr={curr}");
This will print:
Before 'for' loop: curr=0
In 'for' loop: curr=0 ousideCurrRef=0
In 'for' loop: curr=1 ousideCurrRef=0
In 'for' loop: curr=2 ousideCurrRef=0
In 'for' loop: curr=3 ousideCurrRef=0
After 'for' loop: curr=0
Thus the curr outside the for loop won't change if you modify a variable of the same name inside the for loop.

Resources