简体   繁体   English

使用列表库进行递归列表搜索

[英]List-Search with recursion by using list library

int listRecSearch(list<int>list, const int data)
{
  if (list.empty())
  {
    cout << "The number is not in the list, try again..." << endl;
    return -1;
  }
  else if (list.back() == data)
  {
//    cout << "list.size(): " << list.size() << endl;
    list.pop_back();//I needed the index begins from 0 instead of 1
    return list.size();
  }
  else
  {
//    cout << "list.back(): " << list.back() << endl;
    list.pop_back();
    listRecSearch(list, data);
  }
}

//funtion used
int main()
{
 list<int>list = listGenerator(size);//generate a list with 20 random numbers.
 cout << "Specify the element to be searched for: ";
 cin >> data;
 int position = listRecSearch(list, data);
 if (position > -1)
    cout << "\nFind the element at position: " << position << endl;
}

The function listRecSearch was able to display correct list.size() value and correct pop_back values. 函数listRecSearch能够显示正确的list.size()值和正确的pop_back值。 But once it returned, it always return a garbage value. 但是一旦返回,它总是返回一个垃圾值。 I figured there were steps were still went through after return, but I can't see where and how. 我以为返回后仍然有步骤要走,但我看不到哪里和如何做。

There exists a code path which does not return a value. 存在一个不返回值的代码路径。 listRecSearch(list, data); should become return listRecSearch(list, data); 应该成为return listRecSearch(list, data); .

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

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