2016-03-01 71 views
0

我正在写一个C++程序,将采取2列表,L和P,并试图写一个方法,将打印在P中指定位置的L中的元素。下面是代码:C++ void方法得到一个无效的错误

#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)我是说,是的功能是无效的,但是那是因为它被认为是。这个函数不返回任何东西,所以我不知道为什么它给我这个函数的错误是无效的。我不知道如何解决这个问题。任何帮助?

+3

在printLots函数中,您不设置类型。像列表 Chuck

+0

好吧,我修好了,那是我的问题。非常感谢。 – GenericUser01

回答

2

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

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

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

如果您需要它来处理多种类型,您可以使printLots为模板化函数。

此外,你可能想通过const list<int>&避免复制列表,因为你没有改变它们。

相关问题