【发布时间】:2014-11-13 00:05:57
【问题描述】:
我有一个具有std::vector<std::unique_ptr<T>> 的类,我想在std::unique_ptr 持有的指针的引用上创建一个迭代器。
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
class Pointer
{
public:
Pointer() {}
~Pointer() {}
void printSomething()
{
std::cout << "Hi" << std::endl;
}
};
class Keeper
{
public:
typedef std::vector<std::unique_ptr<Pointer>> vector_type;
Keeper() {}
virtual ~Keeper() {}
void push_back(vector_type::value_type pointer)
{
data.push_back(pointer);
}
vector_type::const_iterator begin() const
{
return data.begin();
}
vector_type::const_iterator end() const
{
return data.end();
}
private:
vector_type data;
};
int main()
{
Keeper keeper;
keeper.push_back(std::make_unique<Pointer>());
std::for_each(keeper.begin(), keeper.end(), [] (auto pointer) {
pointer.printSomething();
});
}
我遇到了一连串的错误,我不能放在这里...
如何提供一个接口来通过std::unique_ptr的引用进行交互?
【问题讨论】:
-
法向量迭代器有什么问题?
-
你想做什么?
vector的迭代器类型有一个typedef。 -
我想最好交换声明并改用
std::unique_ptr<std::vector<Pointer> >。 -
我已将其作为重复项关闭,因为我认为您要问的是“我如何获得一个在取消引用时返回
Pointer的迭代器,而不是unique_ptr<Pointer>?”如果这不是您要问的,请澄清问题并重新打开它。