gpt4 book ai didi

c++ - C++ initializer_list迭代器返回错误值

转载 作者:行者123 更新时间:2023-12-02 09:51:16 24 4
gpt4 key购买 nike

我有一个这样定义的类:

initializer_list<string> choices;
initializer_list<string>::iterator current_choice;
bool has_choices = false;
MenuItem(Position position, string prompt) { this->position = position; this->prompt = prompt; }
MenuItem(Position position, string prompt, initializer_list<string> choices) : MenuItem(position, prompt) {
this->choices = choices;
this->current_choice = this->choices.begin();
this->text = *(this->current_choice);
this->has_choices = true;
}

当前菜单项定义为
MenuItem * current_menu_item =&menuItems [menuItemIndex];

当我遍历构造函数中的initializer_list时,将输出正确的值。但是稍后在代码中,当我尝试切换值时,如下所示:
 if (c == KEY_RIGHT) {
if (current_menu_item->has_choices)
{
if (current_menu_item->current_choice != current_menu_item->choices.end()) {
current_menu_item->current_choice++;
current_menu_item->text = *(current_menu_item->current_choice);
}
}
}

它显示了下一个菜单项对象的initializer_list的第一个值,然后按向右键,然后崩溃。如果选择了下一个对象,然后按向右键,它将崩溃。

像这样将对象放入 vector 中
menuItems.push_back(MenuItem(Position(5, 15), "Religion: ", { "*", "*", "*", "Protestant" }));
menuItems.push_back(MenuItem(Position(30, 5), "Do you smoke? ", { "Yes", "No" }));

我已经尝试在整个代码的各个阶段进行调试,但是似乎无法查明哪里或为什么会出错。

没关系,两个人指出我应该使用常规容器而不是initializer_list。感谢大家的回答。我现在觉得很蠢。我要做的就是将initializer_list更改为 vector ,而无需更改任何其他代码。我爱C++。

最佳答案

摘自“Working Draft C++,2012-11-02”

18.9 Initializer lists [support.initlist]
2 An object of type initializer_list provides access to an array of objects of type const E. [ Note: A pair of pointers or a pointer plus a length would be obvious representations for initializer_list. initializer_list is used to implement initializer lists as specified in 8.5.4. Copying an initializer list does not copy the underlying elements. — end note ]



例如,如果我将初始化程序列表复制到 std::vector中,则效果很好。您应该将 choices定义为常规容器,而不是 std::initializer_list
#include <string>
#include <vector>
#include <iostream>
#include <iterator>

struct A {
A(const std::initializer_list<std::string> &args) : v(args) {}
void dump() {
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}

std::vector<std::string> v;
};

int main(int argc, char **argv)
{
A a({"Hello, ", "world!"});
a.dump();
return 0;
}

关于c++ - C++ initializer_list迭代器返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com