Hello fellow programmers,
I am having an issue with using std::upper_bound and std::lower_bound in my code. I have been trying to debug this for quite some time, and I will post my issue and what my thought process is.
To start, I have a class that has two variables (unsigned long and string), and I have a vector that is of type that structure. The vector is sorted by each class' unsigned long. The program will take in 2 numbers in cin and try to find how many numbers fit within this interval.
class thing{
public:
unsigned int x;
string y;
};
// this is the first comparator for the lower bound
bool comp1(thing a, unsigned long b)
{ return a.x < b;}
// this is the second comparator for the upper bound
bool comp2(unsigned long b, thing a)
{ return a.x >= b;}
int main()
{
vector<thing> vec;
// set elements of this vector, then it is sorted according to its unsigned long.
std::vector<thing>::iterator itlow;
std::vector<thing>::iterator ithigh;
unsigned long a = 0;
unsigned long b = 0;
string temp;
while(getline(cin, temp))
{
a = temp[0];
b = temp[2];
itlow = std::lower_bound(vec.begin(), vec.end(), a, comp1);
ithigh = std::upper_bound(vec.begin(), vec.end(), b, comp2);
cout << std::distance(itlow, ithigh) << endl;
}
}
The problem appears when the first cin numbers are 0 (which is not contained in the vector), and the second to smallest unsigned long. This will give me a distance of 1. But then when I cin 0 and the smallest unsigned long, the distance becomes a random number and the upper bound is equal to the zeroth position in the vector.
I know this is quite a lot of code, but I am really stuck and can not figure out why I am having this issue! Thanks again
Aucun commentaire:
Enregistrer un commentaire