这是我第一次询问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)
}
答案 0 :(得分:4)
如果你想避免为你的矢量的每个条目声明一个变量,你可以采取以下几种方式:
使用临时IntRect
插入元素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}
});
答案 1 :(得分:-1)
使用数组,例如:
sf::IntRect WALK_UPs[8] = {
sf::IntRect(80, 526, 32, 48),
sf::IntRect(144, 526, 32, 48),
sf::IntRect(208, 526, 32, 48),
sf::IntRect(272, 526, 32, 48),
sf::IntRect(336, 526, 32, 48),
sf::IntRect(400, 526, 32, 48),
sf::IntRect(464, 526, 32, 48),
sf::IntRect(528, 526, 32, 48)
};
for (int i = 0; i < 8; ++i) {
WALK_UP.push_back(WALK_UPs[i]);
}
在这种情况下,你可以使用迭代器进行初始化,如果这些是被推入容器的唯一元素(我假设你使用的是std::vector
):
WALK_UP = std::vector<sf::IntRect>(WALK_UPs, WALK_UPs+8);
或者,如果您仍然需要单个变量(例如,如果它们用于其他目的),您可以使用指针数组:
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);
sf::IntRect* WALK_UPs[8] = {
&WALK_UP0,
&WALK_UP1,
&WALK_UP2,
&WALK_UP3,
&WALK_UP4,
&WALK_UP5,
&WALK_UP6,
&WALK_UP7,
};
for (int i = 0; i < 8; ++i) {
WALK_UP.push_back(*(WALK_UPs[i]));
};
答案 2 :(得分:-2)
如果您尝试在WALK_UP结束时复制WALK_UP的当前内容,则可以执行以下操作。请注意,由于迭代器失效,某些人可能会遇到的方式(例如使用带有std :: back_inserter的std :: copy)可能不安全,具体取决于WALK_UP的类型。
for(size_t ndx = 0, count = WALK_UP.size(); count>ndx; ++ndx)
WALK_UP.push_back(&WALK_UP[ndx]);