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

Homework: Counting number of times an item occurs in a linked list

本文关键字:链表 项目 计算 一个 作业      更新时间:2023-10-16

赋值如下:实现一个方法countValue(),计算一个项目在链表中出现的次数。请记住使用STL列表。

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

生成20个0 ~ 4范围内的随机数,将每个数字插入链表。使用一个称为writeLinkedList的方法输出列表,并将其添加到ListP.cpp。

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

请记住,上述所有内容都将包含在文件ListP.ccp中输入:2 3 4 0 1 0 2 4 2 3 3 4 3 3 0 0 2 0 2 20: 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上查看了教程,但我仍然不能弄清楚这一点。感谢所有有用的信息!

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

然后想想你在这里看什么:
错误C2039: 'item':不是'std::list<_Ty>'的成员,第34、38、42、46、49行
很可能是你打了个小错别字,我让你自己纠正;)

对你来说是个开始