我最初用Python创建了这个游戏,然后在一个学校项目中将它转换为C++.
问题是C++ std::list不允许我访问像Python的list那样的项(list[1]更多),访问列表中的列表项(list[2][5]).我无法找到一种有效的方法来做到这一点或替代可行的列表.
5go*_*der 12
不要使用std::list.它实现了一个双向链表,它不提供下标运算符,因为链表的随机访问不能以恒定的复杂度实现.
相反,使用a std::vector实现动态增长的数组,并定义下标运算符.
正如@ShadowRanger所评论的那样,您可能也觉得std::deque有用.它支持恒定时间随机访问,std::vector但此外还具有在删除元素时自动释放存储的功能.(因为std::vector,你必须通过调用显式地执行它shrink_to_fit,并且很容易走错方向.)当你需要在开头和结尾添加元素时,它也是优越的.但据我了解,您无论如何都不想更改容器中的元素数量.
另请注意Python和C++之间的另一个区别.在Python中,如果你写
my_things = [1, 2, 3, 4]
your_things = [5, 6, 7]
our_things = [my_things, your_things]
Run Code Online (Sandbox Code Playgroud)
然后your_things和our_things[1]指向同一个列表.这是因为Python中的对象是引用引用的.另一方面,在C++中,容器具有值语义.也就是说,如果你写
std::vector<int> my_things = {1, 2, 3, 4};
std::vector<int> your_things = {5, 6, 7};
std::vector<std::vector<int>> our_things = {my_things, your_things};
Run Code Online (Sandbox Code Playgroud)
our_things将包含副本的my_things和your_things以及在改变不会影响其他.如果这不是您想要的,您可以改为一次定义嵌套列表.
std::vector<std::vector<int>> our_things = {
{1, 2, 3, 4}, // my things
{5, 6, 7}, // your things
};
Run Code Online (Sandbox Code Playgroud)