作业:计算项目在链接列表中出现的次数

时间:2011-11-16 01:32:52

标签: c++ count linked-list

这是作业: 实现方法countValue(),该方法计算项目在链接列表中出现的次数。请记住使用STL列表。

int countValue(list<int> front, const int item);

生成0到4范围内的20个随机数,并在链表中插入每个数字。使用您将调用writeLinkedList的方法输出列表,该方法将添加到ListP.cpp。

在循环中,调用方法countValue(),并在列表中显示0到4中每个值的出现次数。

请记住,以上所有内容都包含在ListP.ccp文件中 运行:2 3 4 0 1 0 2 4 2 3 3 4 3 3 3 0 0 2 0 2 0:5,1:1,2:5,3:6,4:3

这是我到目前为止所做的:

#include<iostream>
#include<list>
#include<tchar.h>

int countValue(list<int> front, const int item);

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    list<int> front;
    int listCount;
    cout << "Enter the size of the list: ";
    cin >> listCount;
    for (int i = 1; i <= listCount; i++)
        front.insert(rand()%5);
    cout << "Original List of Values: " << endl;
    //writeLinkedList(front, " ");
    cout << endl;
    for(int j=0;j<5;++j)
        cout << countValue (front,j) << endl;
    cout << endl;
    return 0;
}

int countValue(list<int> front, const int item)
{   
    int count0;
    int count1;
    int count2;
    int count3;
    int count4;
    list<int> *List;

    for(list<int>::iterator i = front.begin(); i != front.end(); i++)
    {
        if(List->item == 0)
        {
            count0++;
        }
        if(List->item == 1)
        {
            count1++;
        }
        if(List->item == 2)
        {
            count2++;
        }
        if(List->item == 3)
        {
            count2++;
        }if(List->item == 4)
        {
            count4++;
        }
    }
}

以下是错误:

error C2065: 'list' : undeclared identifier line 5
error C2062: type 'int' unexpected line 5
error C2661: 'std::list<_Ty>::insert' : no overloaded function takes 1 arguments line 16
error C3861: 'countValue': identifier not found line 21
IntelliSense: no instance of overloaded function "std::list<_Ty, _Ax>::insert [with _Ty=int, _Ax=std::allocator<int>]" matches the argument list line 16
IntelliSense: too few arguments in function call line 16
error C2039: 'item': is not a member of 'std::list<_Ty>' lines 34, 38, 42, 46, 49
IntelliSense: declaration is incompatible with "int countValue" (declared at line 5) line 25
IntelliSense: class "std::list<int, std:: allocator<int>>" has no member "item" lines 34, 38, 42, 46, 49

我只是想知道我做错了什么以及如何修复它,如果有人可以帮我弄清楚我是否在执行countValue函数错误或根据说明我真的很感激。我已经多次阅读了教科书中的章节,在youtube和Dream in Code上查阅了教程,但我仍然无法弄清楚这一点。所有有用的信息表示赞赏!

1 个答案:

答案 0 :(得分:3)

首先使用'namespace std;'放行在您的导入之后,在列表声明之前,这将清除一些错误。

然后想想你在这里看到的是什么:
错误C2039:'item':不是'std :: list&lt; _Ty&gt;'的成员第34,38,42,46,49行 这可能是你写了一个小错字,我会让你自己抓住它;)

这是你的开始

相关问题