如何使用 std::back_inserter 插入到容器中(只有一个指向容器的指针)
How to use std::back_inserter to insert into a container (only have a pointer to container)
我想从 foo 转换为 bar。
struct A
{
explicit A(int d): m_d(d) {};
private:
int m_d;
};
A some_function (int i) { return A(2*i); }
std::vector<int> foo;
std::vector<A> bar; // This is part of a Library not under my control
接口只提供pbar
std::vector<A>* pbar =&bar; // This is the interface to the part of a Library not under my control
取消引用 pbar 并将其用作 back_inserter 的参数是否合法?为什么?
std::transform (foo.begin(), foo.end(), std::back_inserter(*pbar), some_function);
这里有一个完整的例子:http://coliru.stacked-crooked.com/a/2aec8d000cabf78b
是的,这样做完全没有问题。我不太确定你困惑的根源是什么,所以我不确定如何回答 "why." 如果你有一个非 const
指向对象的指针,你可以取消引用它并将其传递给需要非 const
引用的函数(如 std::back_inserter
)。
我想从 foo 转换为 bar。
struct A
{
explicit A(int d): m_d(d) {};
private:
int m_d;
};
A some_function (int i) { return A(2*i); }
std::vector<int> foo;
std::vector<A> bar; // This is part of a Library not under my control
接口只提供pbar
std::vector<A>* pbar =&bar; // This is the interface to the part of a Library not under my control
取消引用 pbar 并将其用作 back_inserter 的参数是否合法?为什么?
std::transform (foo.begin(), foo.end(), std::back_inserter(*pbar), some_function);
这里有一个完整的例子:http://coliru.stacked-crooked.com/a/2aec8d000cabf78b
是的,这样做完全没有问题。我不太确定你困惑的根源是什么,所以我不确定如何回答 "why." 如果你有一个非 const
指向对象的指针,你可以取消引用它并将其传递给需要非 const
引用的函数(如 std::back_inserter
)。