迭代一对列表,列表在数组中

Iterating over list of pairs, the list being in an array

本文关键字:列表 数组 迭代      更新时间:2023-10-16

我已经搜索了宇宙最远的地方(也就是互联网),但没有找到一个关于如何解决我的问题的提示。所以我来找你。

我正在尝试迭代一个包含字符串对的列表。这个列表是数组中20个列表中的一个。这是我当前的代码:

logging.h:

#ifndef LOGGING_H
#define LOGGING_H
#include <iostream>
#include <list>
#include <string>
class logging
{
    public:
        void log(int,std::string,std::string);
        void draw();
        logging();
        virtual ~logging();
    private:
        int displaylevel=0;
        std::list<std::pair<std::string,std::string>> logd[20];
};
#endif // LOGGING_H

logging.cpp:

#include "logging.h"
#include <list>
#include <string>
#include <iostream>
logging::logging(){
    //for future use
}
void logging::log(int level,std::string category, std::string entry) {
    int thislevel;
    for (thislevel=level-1;(thislevel>-1);thislevel--){
            std::pair <std::string,std::string> newentry;
            newentry = std::make_pair (category,entry);
            logd[thislevel].push_front(newentry);
    }
}
void logging::draw(){
    //draw console on the screen using opengl
    std::list<std::pair<std::string,std::string>>* log = &(logd[displaylevel]);
    std::list<std::pair<std::string,std::string>>::iterator logit;
    for ( logit = (*log).begin() ; logit != (*log).end() ; logit++ ) {
            std::cout << (*logit).first() << std::endl << (*logit).second() << std::endl;
    }
}
logging::~logging() {
    //Deconstructor for log class (save log to file?)
}

这个想法是,如果一个重要事件5被记录,那么它将被放入列表0,1,2,3和4。通过简单地显示与该详细级别(由displaylevel定义)相对应的列表,可以在游戏中显示各种详细级别(如果控制台/日志打开)。然而,我似乎不能正确地迭代列表,它一直抛出一个不匹配调用std::basic_string错误。任何帮助都很感激,我对c++很陌生。

firstsecondstd::pair的成员变量,而不是成员方法。去掉括号:

std::cout << (*logit).first << std::endl << (*logit).second << std::endl;

您不需要()来访问std::pair成员的.first.second。它们是变量成员,不是方法。

删除它们:

std::cout << (*logit).first() << std::endl << (*logit).second() << std::endl;
                           ^^                                ^^

first &第二,它们不是成员函数。你不能像使用函数一样使用它们。去掉括号。此外,除了将logd设置为数组之外,还可以使用像这样的向量

std:: vector>> log;

还可以防止不必要的内存分配。