gpt4 book ai didi

c++ - STL vector 中值的索引范围的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:32 25 4
gpt4 key购买 nike

我有一个数据表,如下所示。这里需要注意的是keyID可以重复。我收集了以下 vector 结构中的数据,这些数据已排序。

struct myData {
int keyID;
int value;
}

vector<myData> vecReadFromFile;

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

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

基本上我想有效地找到给定键值的索引范围。我已经添加了代码,但现在的代码似乎不适用于上面的示例我提到了什么是错误?

我可以更改逻辑以使用 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

我这里有一些代码

 //==========================================================================
// 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;
}

感谢您的时间和帮助

最佳答案

std::equal_range算法。

关于c++ - STL vector 中值的索引范围的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12215749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com