stl向量中索引值范围的算法

ven*_*rty 1 c++

我有一个数据表,如下所示.请注意,keyID可以是重复的.我已经在矢量结构中收集了以下数据,并对其进行了排序.

struct myData {
   int keyID;
   int value;
}

vector<myData> vecReadFromFile;
Run Code Online (Sandbox Code Playgroud)

现在用户输入一个特定的keyID,我必须检查该值是否在向量中退出,如果退出,我必须返回该值.如果不是,我必须检查它落在哪个值之间,例如,如果用户输入120030,值在120028和120039之间,我应该得到这些值的索引,即此示例中的lowerIndex和upperIndex为'2'和'3'(作为向量index从0开始)

如果用户输入较少的keyID,即120001则不返回任何值.类似地,用户输入的keyID大于最后一个键值,然后返回不同的错误代码.

基本上我想有效地找到给定键值的索引范围.我添加的代码似乎不适用于上面的例子我提到什么是bug?

我可以改变逻辑以使用STL提供的算法.请建议.

我们如何在C++中有效地实现这种算法?请求示例代码作为函数.请注意,我将在我的项目中多次调用函数,因此它必须有效.

keyID   Value   

120002  10  
120025  20  
120028  25  
120039  30  
120042  -   
120048  40  
120052  50  
120112  60  
120117  70  
120123  70  
120126  80  
120130  90  
Run Code Online (Sandbox Code Playgroud)

我这里有一些代码

 //==========================================================================
// FindBounds
bool FindBounds(const KEY& cTarget, UINT& uLower, UINT& uUpper)
{
  uLower = -1;
  uUpper = -1;

  // start with full range of data.
  uLower = 0;
  uUpper = m_uCount-1; // Here I have m_uCount as vector.size()

 // narrow the bounds as much as possible.
 while (uUpper - uLower > 1 && cTarget != m_pKeys[uLower])
 {  
    // split the range in half and discard the half that the key does not belong to. 
    UINT uBound = uUpper - (uUpper-uLower)/2;
    // keep the lower range.
    if (KeyInRange(uLower, uBound, cTarget))
    {
       uUpper = uBound;
    }
    // keep the upper range.
    else
    {
      uLower = uBound;
    }
 }

}

bool KeyInRange(UINT uLower, UINT uUpper, const KEY& cTarget)
{
    // check if target is within range.
    if (m_pKeys[uLower] <= cTarget)
    {
    if (m_pKeys[uUpper] > cTarget || (m_pKeys[uLower] == cTarget && m_pKeys[uLower] == m_pKeys[uUpper]))
    {
            return true;
    }
     }
    // target is not within range.
    return false;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间和帮助

Ros*_*ost 5

std::lower_bound()来自STL,<algorithm>标题:http: //en.cppreference.com/w/cpp/algorithm/lower_bound