简体   繁体   English

自定义搜索功能无法正常工作

[英]Custom search function not working properly

I have written following function, it takes a "block" as an argument, searches for the "block" in a list of blocks "lru". 我已经编写了以下函数,它以“ block”作为参数,在“ lru”块列表中搜索“ block”。 Here "block" is an instance of class "Block". 这里的“块”是类“块”的一个实例。 Following is the declaration of "lru": 以下是“ lru”的声明:

  list<Block> lru;

And following is my search function: 以下是我的搜索功能:

int LRU::searchLRU(Block block)
{
    if (lru.size() == 0) 
    {
        lru.push_back(block);
        return 1;
    }

    list<Block>::iterator i;

    for (i = lru.begin(); i != lru.end(); i++)              
    {
        if (i->get_set() == block.get_set() && i->get_index() == block.get_index()) 
        {
            lru.push_back(block);
            lru.erase(i);
            return 2;
        }
    }

    if (lru.size() == size)
    {
        lru.pop_front();
        lru.push_back(block);
        return 3;
    } 
}

But the problem is sometimes the function returns "0". 但是问题是有时函数会返回“ 0”。 And as a result of that my overall program is not functioning properly. 结果,我的整体程序无法正常运行。 I feel i have handled all the cases. 我觉得我已经处理了所有情况。

Could someone point out the mistake, or why the function returns "0". 有人可以指出错误,或者函数为什么返回“ 0”。

The first if covers the empty list case, the last if covers the full list case, the middle for loop cover the not empty not full list but if you don't find the block you will not return from it, so if it's neither full nor empty you'll return 0 by falling off the end of the function. 第一个if覆盖空列表的情况,最后一个if覆盖完整列表的情况,中间的for循环覆盖不为空的不完整列表,但是如果您找不到该块,则不会从中返回,因此如果该块都不完整也不为空,通过退出函数结尾将返回0。 If it wasn't clear, I'll try to rephrase: 如果不清楚,我将尝试改写:

empty list -> add item, return 0
full list -> pos item, add item, return 3
partially full list -> find item, *if found* {erase item, add item, return 2}

The problem is if found, if you don't find it, you don't do anything. 问题是如果找到,如果找不到,您什么也不做。 You'll fall off the end (and that returns 0 in main, is UB otherwise, see here ). 您将掉到头(在main中返回0,否则为UB, 请参见此处 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM