Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Hey I'm looking for a function to get from the list:
[6, 54, 3, 6, 3]
the following list:
[0, 3]
when I filter on 6.
So far, I've only found functions that let me filter on the first or last occurrence.
There's currently no single function in the standard library for this, but it's easy to write your own, e.g.:
fun <E> Iterable<E>.indexesOf(e: E)
= mapIndexedNotNull{ index, elem -> index.takeIf{ elem == e } }
This will work on any list, collection, or other iterable, of any type, and returns a List<Int>. If there are no matching items (e.g. if the collection is empty), it returns an empty list.
Here mapIndexedNotNull() transforms the elements, returning only the non-null ones. And takeIf() is used to get the index only of matching elements, returning null for the rest (which will then be discarded).
This should be relatively efficient; it does a single scan through the list, and creates only a single new list with the results. (If temporary objects were a major concern, you'd probably not store the matching indices in a list at all, but simply loop through them with some forEachMatchingIndex() function instead.)
(Thanks to Michael for the initial idea.)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
So I'm currently learning 2D arrays in c++, I was solving this question which had a 2D array and we were to use sort inbuilt sort function of c++ with comparator, here's the code:
int getLights(vector<vector<int>>& lights) {
sort(lights.begin(),lights.end(),
[](const auto& a, const auto& b){
return a[0]==b[0] ? a[1]>b[1] : a[0]<b[0];
});
I'm not able to understand how this sort function works, can anyone help me get the output with this input:
lights = [[5,5],[6,3],[3,6]]
The C++'s built in sort that you are using takes the first and last element of the array to be sorted to know what has to be sorted. The third argument is a "comparator", i.e. a function that takes two arguments and returns true if the first argument should come before the second.
In your case a vector a comes before other b if its first element a[0] is smaller the other's b[0], and if they are the same then a comes first if a[1] > b[1].
To archive this logic the conditional operator (E1 ? E2 : E3) is used, which checks the truth value of the first expresión and returns the second if it's true and the third expresión if it's false.
C++ STL provides a function sort that sorts a vector or array (items with random access)
It generally takes two parameters, the first being the point of the
array/vector from where the sorting needs to begin and the second
parameter being the length to which we want the array/vector to get
sorted. The third parameter is optional and can be used in cases where
we want to sort the elements lexicographically.
By default, the sort() function sorts the elements in ascending
order.
How to sort in a particular order?
We can also write our own comparator function and pass it as a third
parameter. This “comparator” function returns a value; convertible to
bool, which basically tells us whether the passed “first” argument
should be placed before the given “second” argument or not.
Source: Sort C STL
The function you have written as the 3rd argument act as a comparator (it is a lambda expression), which returns a boolean value.
return a[0]==b[0] ? a[1]>b[1] : a[0]<b[0];
This statement basically compares the elements of a and b, if 1st element is the same check for the second element. It returns the smallest of the two numbers with respect to the 1st element of both arrays.
Output: [[3,6],[5,5],[6,3]]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have the following set and list declarations:
set<mystruct> my_entries;
unordered_map<string, list<_Rb_tree_const_iterator<mystruct>>> mylist;
What I am trying to do is basically insert some specific nodes of the set to the list as well after inserting it into the set.
auto inserted = my_entries.insert(entry);
mylist[name].push_back(*inserted.first);
I get the following error:
error: no matching function for call to
'std::list<std::_Rb_tree_const_iterator<mystruct> >::push_back(const
mystruct&)’
mylist[name].push_back(*inserted.first);
note: no known conversion for argument 1 from 'const mylist’ to
'std::list<std::_Rb_tree_const_iterator<mylist> >::value_type&& {aka
std::_Rb_tree_const_iterator<mylist>&&}'
Any ideas whats gone wrong?
Thanks.
As the comments describe, you should not be attempting to use internal types from the standard library. You can store the iterator as follows:
set<mystruct> my_entries;
unordered_map<string, list<set<mystruct>::const_iterator>> mylist;
// ...
mylist[name].push_back(inserted.first);
Whenever storing iterators, it's important to understand the rules governing when such iterators can become invalid. In the case of std::set::insert you are guaranteed:
No iterators or references are invalidated.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This is the code that I have written
I am getting an error when trying to print out the vector values and I can not figure out why.
I passed the array to the function print(&v1).
Can someone help me figure out why this error is occurring and if there is a better alternative way to print out the vector elements in my function.
You correctly used -> in print1 instead of . (like in print) to operate on the pointer to the vector. This works because x->y is equivalent to (*x).y, meaning you correctly dereferenced the pointer to the vector before accessing it.
Except for []. Here you also have to dereference the pointer before using []. So:
cout << (*v)[x] << endl;
There is no abbreviation (also called "syntactic sugar") for (*x)[] like there is for (*x).y, so you must do it manually.
The error message is confusing because using [] on a pointer is valid - x[y] is equivalent to *(x+y), which means you are doing pointer arithmetics: You use v as if it was a (C-style) array of vectors, and you try to get the xth element from this array of vectors. Lucky for you, the compiler doesn't know how to << a Vector with cout - but if it could, the code would compile and do something you (probably) did not intend.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I have problem finding the solution of my Question over the internet.
I have an integer array with both positive and negative numbers. like below
int arr[] = {56, 1, -1, 89, 89, 7 ,0, 5, 5, 56, 0,9 22, 33,67, 7, -1}
I need to find all the duplicates in the array.
The output need to be displayed (please note order is maintained) as below:
56 -1 89 7 0 5
I know that duplicates can be found using hash in O(n) time. But I have facing problem in maintaining order.
Also I am not quite aware of C++ standard hash.
Can anyone suggest me, how to do it in C++. STL usage is allowed.
Scan the input array for duplicates in reverse order, tracking the last occurrence of duplicates. Then reverse that list, and you'll have a list of duplicates in order of first appearance in the input array.
e.g.
loop from end to start of the input array
add each value to an unordered set
if the value was already present, it's a duplicate. Add it to a list of duplicates
(a map of value->position), replacing any previous value.
After scanning the input array completes, sort the duplicate list by position, and put those values into a list.
Using an unordered set and a separate duplicate-list with a position reduces storage overhead compared to every entry (even non-duplicates) having a position and a duplicate-count. It also reduces the time taken if there are only a few duplicates. (Since you don't have to walk through the whole set of all values finding only the ones with repeat-count > 1.)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Lets say we have the vectors A and B which
contain objects not primitive data.
The B vector would contain information about which elements to
be removed from the vector A. I don't want to rely on index if possible.
I suspect that in Java this could be done with a method call
to removeAll where you pass the list of things to be
removed as an argument.
Is this possible with the C++ language?
Thanks!
If the vectors are sorted, you can make use of std::set_difference. In fact of you don't sort them first you can't get better than n^2 in terms of complexity. So my suggestion is: sort the vectors and use set_difference.
Without knowing the specifics of what A and B contain, it is possible to do something like this:
std::vector<int> A;
std::vector<int> B;
// fill in your vectors
A.erase(std::remove_if(A.begin(), A.end(), [&](int i)
{
return std::find(B.begin(), B.end(), i) != B.end();
}), A.end());
This will search B for anything that matches in A. If something is found, it will be removed.
This process can be decomposed into:
1) Choose the comparison method that qualifies an element to be deleted,
2) Find a way to delete the selected elements (either as a continuous range or one by one).
Why should this be a problem at all? You only have to find a way to compare the elements on vector B with the elements on vector A, and based on that, you build a list of the elements to be removed, and then you remove them.
Your vector, of course, could be a vector of some class, which contains all the properties you need to do the comparison between the objects in A and B.