C++ void 方法因无效而出错



我正在编写一个C++程序,该程序将采用 2 个列表 L 和 P,并尝试编写一种方法来打印 L 中位于 P 中指定位置的元素。这是代码:

#include <iostream>
#include <list>
#include <iterator>
#include <stdlib.h>
using namespace std;
void printLots( list L, list P );
int main()
{
  list< int > numList = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
  list< int > indexList = {2, 4, 6, 8, 10};
  printLots( numList, indexList );
  return 0;
}
void printLots( list L, list P )
{
  int count;
  list::iterator itrIndex;
  list::iterator itrValue;
  for( itrIndex = P.begin(); itrIndex != P.end(); ++itrIndex )
  {
    count = 1;
    for( itrValue = L.begin(); itrValue != L.end(); ++itrValue )
    {
      if( count == *itrIndex )
      {
    cout << "Value in list L at index " << *itrIndex << " = " << *itrValue << endl;
      }
      ++count;
    }
  }
}

出于某种原因,当我尝试编译时,我收到一个错误说:"error: variable or field 'printLots' declared void void printLots( list L, list P )我的意思是,是的,该函数是无效的,但那是因为它应该是。这个函数不返回任何内容,所以我不知道为什么它会给我一个错误,因为这个函数是无效的。我不知道如何解决这个问题。有什么帮助吗?

在方法的参数中,两个参数的数据类型是没有数据类型的任意列表。您还必须为列表定义数据类型。

list<int>, list<double>, list<...>

您的void printLots( list L, list P )方法未指定列表的类型。尝试void printLots(list<int> L, list<int>P); 您还必须指定实例化迭代器的列表类型。

如果需要printLots处理多种类型,则可以将其设置为模板化函数。

此外,您可能希望传递const list<int>&以避免复制列表,因为您不会更改它们。

最新更新