简体   繁体   English

C++ std::vector 问题 (imgui)

[英]C++ std::vector issue (imgui)

I've had this issue for a while now and I'm not sure exactly how to fix it.这个问题我已经有一段时间了,我不确定如何解决它。

Here's the issue:这是问题:

std::vector<const char*> arr = {};
static char input[48] = "";
ImGui::InputTextWithHint("##Input", "Put your input here", input, IM_ARRAYSIZE(input));

if (ImGui::Button("add to array")){
arr.pushback(input);
}

When I press add, it adds the input into the vector, but if I press add again and change the text, it changes all pushed items of the vector to the input text.当我按下 add 时,它会将输入添加到向量中,但如果我再次按下 add 并更改文本,它会将向量的所有推送项更改为输入文本。 Can anyone help?任何人都可以帮忙吗?

You are pushing the same pointer to the array each time.您每次都将相同的指针推送到数组。 You would have to allocate a new string with the buffer's contents after pressing the button.按下按钮后,您必须为缓冲区的内容分配一个新字符串。

if (ImGui::Button("add to array")){
  char* inputS = (char*)malloc((strlen(input) + 1) * sizeof(*input));  // allocate a separate string
  strcpy(inputS, input);        // copy until the first \0 byte is reached 
  arr.pushback(inputS);
}

This is C-style, which some people might not want to see in modern C++.这是 C 风格,有些人可能不想在现代 C++ 中看到。 You can do the same thing by declaring your array as std::vector<std::string> , which would make it so that when you push a new element to the vector, the constructor of std::string that takes const char* will be called (which is somewhat similar to the C-version).您可以通过将数组声明为std::vector<std::string>来做同样的事情,这样当您将新元素推送到向量时, std::string的构造函数接受const char*将被调用(这有点类似于 C 版本)。

So just所以就

std::vector<std::string> arr;

if (ImGui::Button("add to array")){
  arr.pushback(input); // const char* input will be copied to the new std::string element of the array
}

ImGUI is a C-API, which means it doesn't understand std::string . ImGUI 是一个 C-API,这意味着它不理解std::string To use std::string with ImGUI, you can use it's .data() (or .c_str() ) method to access it's const char* data pointer.要将std::string与 ImGUI 一起使用,您可以使用它的.data() (或.c_str() )方法来访问它的const char*数据指针。

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

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