如果我有以下向量{10 10 10 20 20 20 30 30}并且我希望函数返回整数的位置= X或直接返回X之后的较小元素,例如,如果我正在搜索11我想要返回2的函数,因为第二个元素(10)是向量中第一个小于11的元素.
我尝试使用lower_bound,但这不起作用.
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
vector<int>::iterator low,up;
sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
low=lower_bound (v.begin(), v.end(), 11); //
up= upper_bound (v.begin(), v.end(), 11); //
cout << "lower_bound at position " << int(low- v.begin()) << endl;
cout << "upper_bound at position " << int(up - v.begin()) << endl;
return 0;
Run Code Online (Sandbox Code Playgroud)
此代码输出:
lower_bound at position 3 …Run Code Online (Sandbox Code Playgroud)