Jeswin Jacob Jeswin Jacob - 9 months ago 38
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

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)


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:
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.

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

If you want any clarifications, please ask.

Answer Source

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());