次のベクトル{101010 20 20 20 30 30}があり、たとえば11を検索している場合のように、Xである整数の位置、またはXの直後の小さい要素を返す関数が必要な場合2番目の要素(10)は、ベクトルの11よりも小さい最初の要素であるため、2を返す関数。
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;
このコードは以下を出力します:
lower_bound at position 3
upper_bound at position 3