这是我第一次询问stackoverflow,所以请让我知道问题是否正确。所以我的代码如下:
sf::IntRect WALK_UP0(80, 526, 32, 48);
sf::IntRect WALK_UP1(144, 526, 32, 48);
sf::IntRect WALK_UP2(208, 526, 32, 48);
sf::IntRect WALK_UP3(272, 526, 32, 48);
sf::IntRect WALK_UP4(336, 526, 32, 48);
sf::IntRect WALK_UP5(400, 526, 32, 48);
sf::IntRect WALK_UP6(464, 526, 32, 48);
sf::IntRect WALK_UP7(528, 526, 32, 48);
WALK_UP.push_back(WALK_UP0);
WALK_UP.push_back(WALK_UP1);
WALK_UP.push_back(WALK_UP2);
WALK_UP.push_back(WALK_UP3);
WALK_UP.push_back(WALK_UP4);
WALK_UP.push_back(WALK_UP5);
WALK_UP.push_back(WALK_UP6);
WALK_UP.push_back(WALK_UP7);
我想知道是否有某种方式可以遍历这些push_back语句(我假设初始化不能通过迭代来完成)。像这样:
for (int i = 0; i < 8; i++)
{
WALK_UP.push_back(WALK_UP + i)
}
最佳答案
如果要避免为 vector 的每个条目声明一个变量,可以采用以下几种方法:
WALK_UP.push_back(IntRect{100, 100, 200, 200});
// or if you are lazy, just write
WALK_UP.push_back({100, 100, 200, 200});
这基本上是相同的,因为唯一可能的参数类型是某种IntRect
(更具体地说是
const IntRect&
(左值)或IntRect&&
(右值),但您基本上不需要知道区别)WALK_UP.emplace_back(100, 100, 200, 200);
在这种情况下,
emplace_back
的参数将转发到IntRect构造函数。 WALK_UP.insert(WALK_UP.end(), {
IntRect{100, 100, 200, 200},
// or again shorter:
{100, 100, 200, 200},
...
{123, 456, 789, 123}
});