I want to specify to the lower_bound function that it should compare only the .first property of a pair and not both of them, as I assume it is default behavior.
In my situation, it's guaranteed the input is ordered, and I need a O(nlogn) solution. I'm not using std::binary_search because I need to access the position so I can get the .second value, as the code below shows.
I've read the documentation already, but I didn't find it clear, there were no specific examples there and a description not longer than a paragraph.
Here's my code, which is not producing the expected behavior:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool comp(pair<string, int> i, string value) {
return (i.first == value);
}
int main() {
vector<pair<string, int>> books;
int n;
cin >> n;
for(int i = 0; i < n; i++) {
string name; int code;
pair<string, int> livro;
cin >> name >> code;
books.push_back(make_pair(name, code));
}
int m;
cin >> m;
for(int j = 0; j < m; j++) {
string consult;
cin >> consult;
auto i = lower_bound(books.begin(), books.end(), consult, comp);
if (i->first == consult) {
if (i->second == 1) {
cout << "Avaliable" << '\n';
}
else {
cout << "Borrowed" << '\n';
}
}
else {
cout << "Not found" << '\n';
}
}
}
You should write comp func like below because you have to let lower_bound function know which value is bigger(or lesser) with two pair correctly in its algorithm.
output is ok