相关疑难解决方法(0)

使用索引避免迭代器失效,保持干净的接口

我创建了一个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)

c++ iterator vector invalidation c++11

9
推荐指数
2
解决办法
1535
查看次数

使用可变模板解包参数列表时获取参数索引

我需要在解包和转换参数列表时获取参数的索引。有没有以下问题的解决方案:

#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*> &params)
{
    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)

c++ templates variadic-templates c++11

3
推荐指数
1
解决办法
2859
查看次数

boost 提供 make_zip_range 吗?

这个关于 SO 的答案中,有一条评论暗示了一个有用的 C++ 构造,类似于make_zip_iterator, 但对于范围:它需要一个范围元组并产生一个新范围 - 其begin()end()迭代器是适当的 zip 迭代器。

现在,这应该不太难实现,但我想知道 - Boost 不是已经以某种方式提供了吗?

c++ boost iterator tuples commutativity

3
推荐指数
1
解决办法
1950
查看次数

如何创建一个包含三种不同类型矢量的矢量

我有三个结构(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++的初学者,因此在这里欣赏更容易理解的答案.

c++ vector c++11

-1
推荐指数
1
解决办法
125
查看次数