可以将lower_bound(来自c++ STL)的结果赋值给整数类型变量吗?

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

本文关键字:赋值 结果 整数 类型变量 STL lower bound c++ 来自      更新时间:2023-10-16

我最近开始使用c++ STL,今天我在我的代码中试用了lower_bound函数。但不幸的是,我得到了错误:

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

我的代码

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;

如果你说迭代器类型变量不能添加到整数类型变量中,下面的代码:

https://github.com/sampritipanda/IOI_Repository/blob/master/ZCO/2013/CHEWING.cpp使用lower_bound的结果赋值给整型变量,通过以下行:

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

请告诉我哪里错了。

注意:lli代表已经用宏定义的long long int

不能将迭代器赋值给整型变量。

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

将返回std::vector<int>::difference_type

对于你的情况,你能做的就是:

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