我创建了一个MemoryManager<T>
类,它基本上是两个指针向量的包装器,用于管理堆分配对象的生命周期.
一个向量存储"活动"对象,另一个向量存储将在下一个添加的对象MemoryManager<T>::refresh
.
选择此设计是为了避免在循环时使用迭代器失效MemoryManager<T>
,因为直接向MemoryManager<T>::alive
向量添加新对象会使现有迭代器无效(如果它的大小增大).
template<typename T> struct MemoryManager {
std::vector<std::unique_ptr<T>> alive;
std::vector<T*> toAdd;
T& create() {
auto r(new T);
toAdd.push_back(r);
return *r;
}
T& refresh() {
// Use erase-remove idiom on dead objects
eraseRemoveIf(alive, [](const std::unique_ptr<T>& p){ return p->alive; });
// Add all "toAdd" objects and clear the "toAdd" vector
for(auto i : toAdd) alive.emplace_back(i);
toAdd.clear();
}
void kill(T& mItem) { mItem.alive = false; }
IteratorType begin() { return alive.begin(); }
IteratorType end() …
Run Code Online (Sandbox Code Playgroud) 我需要在解包和转换参数列表时获取参数的索引。有没有以下问题的解决方案:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void test(int a, std::string b, bool c)
{
cout << a << "," << b << "," << c << endl ;
}
template <typename... ARG>
static void call_test(const vector<void*> ¶ms)
{
test(*static_cast<ARG*>(params[ indexOf(ARG) ])...);
}
int main(int argc, char **argv)
{
int a = 1;
string b = "string";
bool c = false;
vector<void*> v(3);
v[0] = &a;
v[1] = &b;
v[2] = &c;
call_test<int,string,bool>(v);
}
Run Code Online (Sandbox Code Playgroud) 我有三个结构(Foo,Bar,Fruit),我想要一个向量来保存每个结构vector<Foo> Foo_holder; vector<Bar> Bar_holder; vector<Fruit> Fruit holder;
,然后我想尝试将所有这三个向量放入一个向量中.所以它应该像这样结束,Vector_holder
作为我希望知道如何创建的顶级向量:
Vector_holder
--- Foo_Holder
------Instance of Foo
--- Bar_holder
------Instance of Bar
--- Fruit_holder
------Instance of Fruit
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
可能的重复问题列出了一个问题,即向量必须是相同的大小或代码中断,并且我的问题中的向量将大量移动大小.我也觉得这对初学者C++学习者比其他问题更有帮助.我在这里找到的解决方案对我有用,并且总体上比近篇文章的长答案简单得多.我更像是C++的初学者,因此在这里欣赏更容易理解的答案.