【问题标题】:List stl C++ Struct列出 stl C++ 结构
【发布时间】:2012-12-11 00:35:50
【问题描述】:

我在使用 while 循环将数据从文本文件插入 stl 列表时遇到问题。你能帮我理解我的错误吗?非常感谢。 错误是

server3.cpp: In function ‘int main(int, char**)’:
server3.cpp:43:11: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
server3.cpp:74:15: error: ‘class std::list<Record>’ has no member named ‘id’
server3.cpp:74:25: error: ‘class std::list<Record>’ has no member named ‘firstName’
server3.cpp:74:42: error: ‘class std::list<Record>’ has no member named ‘lastName’
server3.cpp:75:12: error: ‘class std::list<Record>’ has no member named ‘id’
server3.cpp:76:17: error: no match for ‘operator[]’ in ‘hashtable[hash]’
server3.cpp:76:50: error: expected primary-expression before ‘)’ token

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <vector>
#include <list>
#include <iostream>
#include <fstream>
using namespace std;

const int SIZE =100;/*size of hashTable*/
/*Struct representing the record*/
struct Record
{
     int id;
     char firstName[100];
     char lastName[100];
} rec;


/*Structure representing a single cell*/
class Cell
{
    std:: list<Record> recs;
    pthread_mutex_t lock;
};

/* The actual hash table */
std::list<Cell> hashtable;



int main (int argc, char * argv[])
{

    ifstream indata; /* indata is like a cin*/
        indata.open("fileName"); /* opens the file*/

    list <Record> rec;/*create an object*/
    int hash;
    while ( !indata.eof() ) /* keep reading until end-of-file*/
    { 
    indata>> rec.id >> rec.firstName >> rec.lastName;
    hash =rec.id % sizeof(hashtable);
    hashtable [hash].listofrecords.push_back (Record);

    }
     indata.close();

   return 0;    



}

【问题讨论】:

    标签: c++ linux list stl


    【解决方案1】:

    他们中的大多数人告诉你list 没有成员,因为你试图这样做

    indata>> rec.id >> rec.firstName >> rec.lastName;
    

    rec 是一个列表,而不是Record

    hashtable[hash]
    

    也是非法的(std::list见接口,而Record是类型,不能在容器中插入类型,只能插入对象:

    ...push_back (Record);
    

    是非法的。

    代码不只是我们不时犯的偶尔错误,而是存在根本缺陷。我建议你从a good book 开始学习 C++(如果你正在这样做的话)。

    【讨论】:

    • 这是什么意思?谢谢。
    • @NatashaLevesque 这意味着你需要从一本可靠的书开始学习 C++。
    【解决方案2】:

    请注意,您正在创建一个记录集合,但这意味着您需要先访问该集合的某个元素,然后才能访问其中包含的记录字段。

    以下是使用列表类型的参考: http://www.cplusplus.com/reference/list/list/

    【讨论】:

      【解决方案3】:

      仅此一条线至少存在三个主要问题。

       hashtable [hash].listofrecords.push_back (Record);
      
      1. std::list 没有 operator[],因此您不能使用 [hash] 下标。
      2. 您的程序中没有任何地方定义过listofrecords 的含义。
      3. 您正在尝试push_back 一个名为Record类型,其中需要一个对象。

      请找一本不错的 C++ 书籍开始学习:The Definitive C++ Book Guide and List

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-08
        • 2023-02-18
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多