简体   繁体   English

std :: vector :: const_iterator未指向所需数据

[英]std::vector::const_iterator not pointing to desired data

I have a std::vector<const char*> named log in a class Gui that I am trying to iterate through and use the values as arguments for a library function. 我在类Gui中有一个名为std::vector<const char*> log ,我试图对其进行迭代,并将这些值用作库函数的参数。 The problem is that it seems to return incorrect/wrongly typed data. 问题在于它似乎返回错误/错误键入的数据。

void Gui::Message(const char *text, ...)
{
    char buffer[256];
    va_list args;
    va_start(args, text);
    vsnprintf(buffer, 256, text, args);
    va_end(args);
    log.emplace(log.begin(), buffer);
}

This formats the string properly and adds it to the vector. 这将正确格式化字符串并将其添加到向量中。 If I call puts(log.front()) after I emplace the buffer, it prints the correct output to the console. 如果我叫puts(log.front())后,我emplace缓冲区,它打印正确的输出到控制台。 Also, if I emplace(text) instead of the buffer, it is displayed properly when Gui::render() is called, but it obviously isn't formatted. 另外,如果我用emplace(text)代替了缓冲区,那么在调用Gui::render()时,它会正确显示,但显然没有格式化。

void Gui::render()
{
    int y = 1;
    for(std::vector<const char*>::const_iterator iter = log.begin();
        iter != log.end(); iter++);
    {
        terminal_color("light grey");
        //takes x and y coordinates and a const char* and prints to the specified cell
        terminal_printf(1, 45 + y, "%s", (*iter));
        y++;
    }
}

Now if I call puts((*iter)) instead of the terminal print function, it still prints the incorrect data, so it doesn't appear to be a problem with the library function. 现在,如果我调用puts((*iter))而不是终端打印函数,它将仍然打印不正确的数据,因此库函数似乎没有问题。

Refactoring the data structure for storing the messages is an option, but the strings need to be able to be properly formatted and passed to the library print function. 重构用于存储消息的数据结构是一个选项,但是字符串必须能够正确格式化并传递给库打印功能。

Your buffer is temporary storage valid only until the Message function returns. 您的缓冲区是临时存储,仅在Message函数返回之前才有效。 You are saving a pointer to where the buffer was, but its contents will be gone before the saved pointer is used. 您正在保存一个指向缓冲区所在位置的指针,但是在使用保存的指针之前,其内容将消失。

If you want something that acts like a string, used std::string , don't misuse const char* 如果您想使用类似于字符串的东西,请使用std::string ,不要滥用const char*

You're not pushing a const char* onto the buffer , you're putting a char that gets erased. 您不是将const char*推送到buffer ,而是将要擦除的char放入。

You use string and make your life easier. 您使用string ,使您的生活更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM