I am new in C++ world.
There is a upper_bound function in a set that returns number greater than passed value. I would like to know if there is any way to get a number lower than the passed value? Let's say if we have {3,6,8,9,11} in set and by passing to my function: func(8), I will receive 6, since 6 is the number that stays before 8.
Any idea?
Your approach is reasonable, but instead of std::upper_bound, you should use std::lower_bound, like this for example:
#include <iostream>
#include <set>
using namespace std;
int main(void)
{
set<int> myset{3, 6, 8, 9, 11};
set<int>::iterator it = myset.lower_bound(8);
if (it != myset.begin()) {
it--;
cout << *it << endl;
} else {
cout << "No smaller element found!" << endl;
}
return 0;
}
Ouptut:
6
Related
#include<bits/stdc++.h>
using namespace std;
int main() {
map<int, int> nums_map;
cout << nums_map.count(0) << endl;
int a = nums_map[0];
cout << nums_map.count(0) << endl;
cout << nums_map[0];
return 0;
}
OUTPUT:
0
1
0
It makes no sense to me at least, why the line:
int a = nums_map[0];
is increasing the value of count by 1, also the nums_map.empty() = 0 at the same time.
Because std::map::operator[] works in a slightly weird way. From the documentation on std::map::operator[]:
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
So if the key doesn't exist, it creates a new pair. That's exactly what's happening here.
#include <iostream>
#include <map>
int main() {
using namespace std;
map<int, int> nums_map; // nums_map == {}
cout << nums_map.count(0) << endl; // 0, because the map is empty
int a = nums_map[0]; /* a new key/value pair of {0, 0} is
created and a is set to nums_map[0],
which is 0 */
cout << nums_map.count(0) << endl; // Since there is one key 0 now, this shows 1
cout << nums_map[0]; // As shown previously, nums_map[0] is 0
return 0;
}
I need to print an array by implementing the use of a function before the main function. So I tried the following function:
int* printArr(int* arr)
{
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
return arr;
}
I encountered two problems when implementing this into the whole code.
First, this is printing what I think is the address of the array and not the actual array. Pretty sure this is because of the return arr; in line 10. But if I do not write return then the code will produce an error. How can I fix this?
Second, I do not understand the second argument printArr has. In line 19, you can see cout << printArr(arr, 5) << endl;. How come there is a single numeric value, that one being 5 in this case, as an argument? How can I account for this in my function?
Please keep in mind that I am new to C++ and coding in general. Also, this code was given to me, hence why I do not understand certain aspects of it.
This is my code so you can see what I mean:
#include <iostream>
using namespace std;
// Declare function printArr here
int* printArr(int* arr)
{
for (int i = 0; i < 5; i++)
{cout << arr[i];}
return arr;
}
int main()
{
int arr[5] = {1, 3, 5, 7,9};
int last_num = arr[sizeof(arr)/sizeof(int)-1];
cout << "Before reversing" << endl;
cout << printArr(arr, 5) << endl;
// reverse "arr" using reference(&)
cout << "After reversing" << endl;
printArr(arr, 5);
return 0;
}
The declaration and implementation of printArr() is all wrong.
First, this is printing what I think is the address of the array and not the actual array.
The printArr() function itself is printing the contents of the array (well, the first 5 elements anyway), and then returning the address of the array. It is main() that is printing that address afterwards, when it passes the return value of printArr() to std::cout <<.
Pretty sure this is because of the return arr; in line 10. But if I do not write return then the code will produce an error. How can I fix this?
By getting rid of the return type altogether. There is no good reason to return the array pointer at all in this example, let alone to pass that pointer to std::cout. So printArr() should be returning void, ie nothing.
Second, I do not understand the second argument printArr has. In line 19, you can see cout << printArr(arr, 5) << endl;. How come there is a single numeric value, that one being 5 in this case, as an argument?
Because main() is passing in the element count of the array (5) so that printArr() can know how many elements to actually print, instead of hard-coding that value in the loop. However, your declaration of printArr() does not have a 2nd parameter with which to accept that value, that is why you are getting errors.
How can I account for this in my function?
By adding a 2nd parameter in the function declaration, eg:
#include <iostream>
using namespace std;
// Declare function printArr here
void printArr(int* arr, int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
}
int main()
{
int arr[5] = {1, 3, 5, 7, 9};
const int count = sizeof(arr)/sizeof(arr[0]);
int last_num = arr[count-1];
cout << "Before reversing" << endl;
printArr(arr, count);
// reverse "arr" using reference(&)
cout << "After reversing" << endl;
printArr(arr, count);
return 0;
}
Live Demo
I have this c++ code which works fine in deleting the last 3 elements of a list, but i was wondering if it's the correct way to do such a thing since i am worried of deleting elements with iterators issues.
The code basically takes a list of 6 elements "Groups", divides it into 2 smaller lists "Group1" and "Group2", and then compares a different List "GroupToCompare" to "Group2" and if they're equal it removes the last 3 elements of "Groups".
#include "pch.h"
#include <iostream>
#include <iostream>
#include <string>
#include <list>
using namespace std;
int main()
{
std::list <string> Groups = {};
Groups = { "Spike", "Jet", "Faye", "Edward", "Vincent", "Elektra" };
std::list<string> Group1 = {};
std::list<string> Group2 = {};
std::list<string> GroupToCompare = {};
GroupToCompare = { "Edward", "Vincent", "Elektra" };
size_t half1 = Groups.size() / 2;
std::list<std::string>::iterator ig = Groups.begin();
advance(ig, half1);
Group1.insert(Group1.end(), Groups.begin(), ig);
Group2.insert(Group2.end(), ig, Groups.end());
std::list<std::string>::iterator removeIt = Groups.begin();
advance(removeIt, half1);
cout << "List Elements 1: " << endl;
std::list<string>::iterator itrofList = Group1.begin();
string firstvar;
for (itrofList = Group1.begin(); itrofList != Group1.end(); ++itrofList) {
firstvar = *itrofList;
cout << "Item: " << firstvar << endl;
}
cout << "List Elements 2: " << endl;
std::list<string>::iterator itrofList1 = Group2.begin();
string firstvar1;
for (itrofList1 = Group2.begin(); itrofList1 != Group2.end(); ++itrofList1) {
firstvar1 = *itrofList1;
cout << "Item: " << firstvar1 << endl;
}
if (Group2 == GroupToCompare) {
removeIt = Groups.erase(removeIt);
removeIt = Groups.erase(removeIt);
removeIt = Groups.erase(removeIt);
}
cout << "List Elements of Groups after removing the last 3 elements: " << endl;
std::list<string>::iterator itrofList2 = Groups.begin();
string firstvar2;
for (itrofList2 = Groups.begin(); itrofList2 != Groups.end(); ++itrofList2) {
firstvar2 = *itrofList2;
cout << "Item: " << firstvar2 << endl;
}
}
is there a more correct way in case i wanna delete more elements in the end of the list and avoid deleting issues with iterators?
Thanks in advance!
Even though calling std::list::erase() multiple times with the returned position works, calling the correct overload would help with readability and possibly performance:
iterator erase( iterator first, iterator last );
Example:
std::list<int> l{1, 2, 3, 4, 5};
l.erase(std::prev(l.end(), 3), l.end());
// l is {1, 2}
Beware: as-is, this code exhibit undefined behavior if l is not at least 3 in size.
Is there a more correct way to do it?
Not sure what that means, but im assuming you would be interested in learning std::list has a public member function pop_back which deletes the last element in a list. Using this seems ideal for your case.
Note: As stated in this refference
If the container is not empty, the function never throws exceptions
(no-throw guarantee). Otherwise, it causes undefined behavior.
So make sure the list is never empty when you call this function.
I would just...
std::list <string> Groups;
...
for (int i = 0; i < 3; ++i)
Groups.pop_back();
I am following this tutorial on Lower_bound() in C++. I have made a simple code to find a number in a vector lesser than or equal to a number from the vector + any number that I want. My code goes like this
cout << *lower_bound(A.begin(), A.end(), A[x] + 3);
where the vector A[] is sorted. But the code points it to a number greater than the sum of both the numbers.
For example if my vector has values as 0, 3, 5, 8, 12 and I want it to print the nearest number lesser than or equal to A[3] + 3 = 11 it should give output as 8 but it gives the output of 12. Any reasons?
Here is my code:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> A = {0, 5, 3, 12, 8};
sort(A.begin(), A.end());
cout << "A[3] = " << A[3] << endl;
cout << *lower_bound(A.begin(), A.end(), A[3] + 3) << endl;
return 0;
}
lower_bound
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
In your case it is not returning the last value less than 11. It returns the first value not less than 11, which in your example is 12.
If you want the largest number not greater than your target, you can use std::greater<> and reverse iterators (or sort by std::greater<>)
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> A = {0, 5, 3, 12, 8};
std::sort(A.begin(), A.end());
std::cout << "A[3] = " << A[3] << std::endl;
std::cout << *std::lower_bound(A.rbegin(), A.rend(), A[3] + 3, std::greater<int>{}) << std::endl;
return 0;
}
I want to implement an insert function in c++ to build a d-max heap. The d is referring to the number of children in the heap and a max heap is a heap which has its' elements structured in a priority (3,2,1...). The heap is supposed to be represented as an array and the function I'm looking for is adding items from the top one by one and then continuing downward. This may seem like an easy task but I'm confused about how this is going to work.
Here is a rough example of the template function:
template <typename Comparable>
void buildHeapTopDown(Comparable arr[], int size, int d)
{
for (int i = 0; i < 5; ++i)
{
arr[0] = 2;
arr[1] = 3;
arr[2] = 4;
arr[3] = 6;
arr[4] = 9;
}
}
Now as this is some really basic code the function is not really informative about the way a d-heap works. What I mean is I have not implemented the theory behind the d-heap, which basically is pretty much the same as the theory behind a binary heap (we only replace 2 with d in the formulas). The formulas for finding a parent and a child for a heap then becomes:
(x-1) / d, x*d + 1 (left child) and x*d + 2 (right child).
I also know there is a way to create a heap using the <algorithm> class, but as these functions are already prepared and they are using vectors, it's not really what I'm looking for.
Example using the algorithm class:
#include <iostream>
#include <array>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int myInts[] = { 1, 2, 3, 5, 4, 7, 10, 13, 15, 6, 8, 17, 9, 11, 9 };
vector <int> v(myInts, myInts + 15);
make_heap(v.begin(), v.end());
cout << "Initial max heap: " << v.front() << endl;
pop_heap(v.begin(), v.end());
v.pop_back();
cout << "Max heap after pop: " << v.front() << endl;
v.push_back(77); // insert example
push_heap(v.begin(), v.end());
cout << "Max heap after push: " << v.front() << endl;
sort_heap(v.begin(), v.end());
cout << "Final sorted range:";
for (unsigned i = 0; i < v.size(); i++)
{
cout << " " << v[i];
}
cout << endl;
getchar();
getchar();
}
Anyone who can give any hints how to do it as the way I described in the top?