Jeswin Jacob Jeswin Jacob - 27 days ago 11
C++ Question

Can the result of lower_bound(From C++ STL) be assigned to an integer type variable?

I recently started using the C++ STL, and today I tried out the

lower_bound
function in my code. But unfortunately, I got the error:

cannot convert '__gnu_cxx::__normal_iterator<long long int*, std::vector<long long int> >' to 'long long int' in assignment|


Here is my code

lli n;
cin >> n;
lli k;
cin >> k;

vector<lli> v;
lli store;
for(lli i = 0;i < n;i++)
{
cin >> store;
if(store < k)
v.push_back(store);
}

sort(v.begin(),v.end());

lli paths = 0;
for(lli i = (lli)v.size()-1;i >= 0;i--)
paths = paths + lower_bound(v.begin(),v.begin()+i-1,v[i]-k);

cout << paths;


If you guys say that an iterator type variable can't be added to an integer type variable,this code:

https://github.com/sampritipanda/IOI_Repository/blob/master/ZCO/2013/CHEWING.cpp
uses the result of lower_bound to be assigned to an integer type variable, through the line:

int j = lower_bound(gum.begin() + i, gum.end(), K - gum[i]) - (gum.begin() + i);


Please advice where I'm going wrong.

Note:
lli
stands for
long long int
which has already been defined using a macro.

If you want any clarifications, please ask.

Answer

No, you can't assign an iterator to an integral variable.

lower_bound(gum.begin() + i, gum.end(), K - gum[i]) - (gum.begin() + i);

will return std::vector<int>::difference_type

The best you can do in your case is:

paths = paths + (lower_bound(v.begin(),v.begin()+i-1,v[i]-k) - v.begin());