Maps and Vectors -STL in C++ - c++

Can anyone explain this code working?It is to find index of 2 elements in vector that add to produce the given target.I don't understand how STL works in this.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int>m;
vector<int>v;
if(nums.size()==0)
{
return v;
}
for(int i=0;i<nums.size();i++)
{
if(m.find(nums[i])==m.end())
{
m[target-nums[i]]=i+1;
}
else
{
v.push_back(m[nums[i]]);
v.push_back(i+1);
}
}
return v;
}
};

It's pretty easy. Say the vector is { 8, 4, 3, 2, 5 } and the target is 10. First number you find is 8, so now you know that you are looking for a 2 (because 8 + 2 is 10). So you add the new target 2 and the index of 8 (which is 1 because the indexes are 1 based) to the map. Next number is 4 so now you are looking for 6, so 6 and the index 2 get added to the map. Now the map looks like this
2 ==> 1
6 ==> 2
Eventually you'll find one of the targets in the map (in this case we'll find a two), the map gives us the index of the original 8, and we know the index of the 2 because we've just found it, so we can output both indexes.
The code could be improved, but I think it works.

Related

C++ 2D Vector initialization with another vector

vector<vector<double>> weights
{
{1},
{1}
};
Above is my code to make a 2x1 vector each holding 1.
I would like to make a matrix of 2xN that I could use to multiply with that vector.
I have seen other stackoverflow questions that talk about creating matrices, and most of the ones I've seen are with fixed values, or user input.
But what I would like to do, is initialize the entire first column of N length with 1s, and the initialize the entire second column with a second vector I already have.
I am unsure how in C++ I could accomplish this. I'm way more familiar with R, and in R this is a pretty simple task. Any thoughts or guidance?
You mean like this?
std::vector<int> vinner {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
std::vector<std::vector<int>> v {
std::vector<int>(10, 1),
vinner
};
int main(int argc, char **argv)
{
for (auto i : v) {
for (auto j : i) {
std::cout << j << " ";
}
std::cout << "\n";
}
return 0;
}
Output:
$ clang++ -o vect vect.cpp -std=c++17
$ ./vect
1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9 10

List filter within the outer range - KOTLIN

I have just started learning kotlin, and I stumbled upon this small issue. I have a list of Objects, and am filtering the list within a specified range. Am able to get the objects with in the range, but when I changed the range to outer bound, am getting an empty array,
So to keep the question simple, lets say am having a list of integers like
original list [1, 2, 3, 4, 5, 6, 7]
and am having a dropper function, which filters out the elements
working condition
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 2..6 } // it >= 2 && it <= 6
}
output is received as
[2, 3, 4, 5, 6]
but when I change the range to
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 4..2 } // it <= 2 && it >= 4
// it in 4..2 , was suggested by the IDE
}
getting output as an empty list.
Am pretty much sure that the list value is not clearing, because after this function is called am passing the list to an other operation which gives the intended result.
4..2 is basically an empty range, because it translates to it >= 4 && it <= 2. To create a range that's decrementing, you have to use downTo:
args.filter { it in 4 downTo 2 }
reversed can also be an alternative in some cases:
args.filter { it in (2..4).reversed() }
This specific problem is also the first example in Dan Lew's recent blog post that covers ranges nicely.
Use downTo. read Ranges for detailed description.
Range (x..y), here x is starting index and y is last and it goes increamental way. So 1..10 range have 10 elements but 10..1 looks from 10 on-wards so it is an empty range. You need to use downTo operator.
Change your code like following:
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 4 downTo 2 } // it <= 2 && it >= 4
}
Hello you need to use operator downTo
fun main(args: Array<String>) {
var list = arrayListOf<Int>(1, 2, 3, 4, 5, 6, 7)
println(dropper(list)) // [2, 3, 4]
}
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it in 4 downTo 2 } // [2, 3, 4]
}
Here is fully described how to use ranges. - https://kotlinlang.org/docs/reference/ranges.html#ranges
Other than these answers, I also found out that ! operation works as well
fun dropper(args: ArrayList<Int>): List<Int> {
return args.filter { it !in 2..4 } // it <= 2 && it >= 4
}

vector erase specific indexes with iterators (not based on range or condition)

Say, I have two vector as follows in the code, I want to erase the elements indexed by vector "index_to_filter" in the vector "data" using iterators. The dummy way in the code is just to point the obvious error. So far, I couldn't get it working, nor, figured out if this could be an erase-remove-idiom?. Is there a way to and am missing it ?
Thx.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> data{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> index_to_filter{ 1, 5, 8 };
/* needed result data = { 0, 2, 3, 4, 6, 7, 9 }*/
std::vector<int>::iterator iter = index_to_filter.begin();
while (iter != index_to_filter.end())
{
std::vector<int>::iterator iter_data = data.begin() + *iter;
iter_data = data.erase(iter_data);
iter++;
}
/* Throws : vector erase iterator outside range */
for (int i: data)
std::cout << i << std::endl;
system("pause");
return 0;
}
PS: the vector.erase question is aborded tens of times here but found no clue for this one !
PS: Solutions without iterators are not welcome. (No offense !)
thanks
Your problem is very simple:
std::vector<int> index_to_filter{ 1, 5, 8 };
You intent is to remove elements #1, #5, and #8 from the other array, and you start with element #1:
Value 0 1 2 3 4 5 6 7 8 9
Index 0 1 2 3 4 5 6 7 8 9
^ ^ ^
The bottom line, the "index" line, is the index into the vector. The top line, the "value" line, is the value in that position in the vector. When you start, the two values are the same.
The carets mark the indexes you wish to remove, and you start with element #1.
The fundamental gap that you are ignoring is that when you remove an element from the vector, you do not exactly have a gaping black hole, a void in that position. All subsequent values in the container shift over. So, when you remove element #1, the remaining values shift over:
Value 0 2 3 4 5 6 7 8 9
Index 0 1 2 3 4 5 6 7 8
^ ^
The next element you wish to remove is element #5. Unfortunately, the value at that position in the vector is no longer 5. It is 6, because the array has shifted. Your code than proceeds and removes index position #5, which has the following result:
Value 0 2 3 4 5 7 8 9
Index 0 1 2 3 4 5 6 7
^
You have already gone off the rails here. But now, your code attempts to remove index #8, which no longer exists, since the vector is now shorter. As soon as your code attempts to do that, you blow up.
So, in conclusion: what you're missing is the simple fact that removing a value from a middle of a vector shifts all subsequent values up by one position, in order to fill the gap left from the removed element, and the code you wrote fails to account for that.
The simplest solution is to remove elements from the highest index position to the lowest. In your code, you already have index_to_filter in sorted order, so instead of iterating from the beginning of index_to_filter to its end, from the lowest to the highest index, iterate backwards, from the last index in index_to_filter to the first, so your code attempts to remove indexes 8, 5, then 1, so that each time the removal of the element does not affect the lower index positions.
If index_to_filter is guaranteed to be sorted, you should be able to just remove the elements in reverse order - the index to filter is still correct as long as no previous entries have been removed.
So just call index_to_filter.rbegin() and index_to_filter.rend() in your current code.

Weird issue with range based for loop

I am working on learning vectors in my C++ object oriented 1 class and we have been introduced the concept of range based for loops. I decided to practice the range based for-loops separately so that I could get used to the syntax but I came across a weird issue.
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
for ( auto i: a)
{
cout << a[i] << " ";
}
return 0;
}
When I run the above code my output is the following.
2 3 4 5 6 7 8 9 0 1 Press any key to continue...
My output should read
1 2 3 4 5 6 7 8 9 0 Press any key to continue...
Can anyone tell me why my first index is skipped? I have visual studio 2013 professional.
You get the weird output because i in the range loop is the value from the array, not an index. That is,
for (auto i : a)
loops through the values of a. In your code you're effectively printing the sequence a[a[0]], a[a[1]], etc.
The code you probably want is
for (auto i : a) {
std::cout << i << std::endl;
}

Most efficient sorting algorithm to continuously sort an vector<vector<double>>

What is the fastest algorithm to keep a
vector<vector<double>>
continuously "merge" sorted being able to handle updates in realtime?
For example, at T0 vec<vector<double> is empty
At T1, (in fact only one vec<double> comes in at once)
A = 1, 2, 4
B = 1, 3, 4, 5
C = 6, 7
The vector<vector> gets merge-sorted into,
1
1
2
3
4
4
5
6
7
At T2
C = 0, 4
D = 3, 7
The new list would be
0
1
1
2
3
3
4
4
4
5
7
So first we have to remove the old values of C, then "insert" the new values of C correctly.
Some sort function like this AVL_Tree Func(vector<vector<double>> vecvec, vector<double> newVec) that returns tree would seem to be best. AVL Tree? Can someone show me a c++ templatized version of code that would work? Boost, STL etc use is fine.