【发布时间】:2012-10-17 15:14:37
【问题描述】:
我感兴趣:
- 具有指向用户定义类型/类的指针的 std::vector
- 以最快的方式填充此向量
我想解决这个问题:
- while + 迭代器(非 C++11 解决方案)
- for_each 迭代 + lambda(c++11 解决方案)
现在在阅读文档后,我正在尝试使用 iterator 部分和 while
#include <iostream>
#include <vector>
class A{
public:
A(){}
~A(){}
private:
int n;
double d;
float f;
std::string s;
};
int main(){
std::vector<A*> v(100); // fixed *A to A*
std::vector<A*>::iterator iter = v.begin(); // fixed *A to A*
while( iter != v.end() )
{
*iter = new A(); // iter = A(); by the way this does not works either // now fixed using new
++iter;
}
return(0);
}
我知道这是微不足道的,但对我来说不是,在我的理解中它是一个指针,需要间接指向它在向量中指向的实际值;显然这个概念不适合这种方式。
对于 lambda 和 for_each,我只是不知道如何为自定义定义的类使用构造函数,因为文档只讨论泛型方法和函数,而且似乎我不能使用构造函数。
如何使用迭代器和 lambda 构建对象?
另外,当我需要在整个地方执行相同的操作而不使用while 和for_each 或for 的迭代方法时,还有一种更快的方法来循环整个向量。
我想避免复制构造函数的开销,所以我想使用指针来保留所有可能的解决方案。
谢谢。
【问题讨论】:
-
难怪它不起作用,你的星号放错地方了。它应该是
std::vector<A*>,而不是std::vector<*A>。您还试图将临时对象分配给指针。 -
@SethCarnegie 我讨厌自己:D
标签: c++ vector constructor lambda iterator