[英]How to create unique pointers in a loop C++?
I am reading a double
from the standard input and saving it into a variable d
.我正在从标准输入中读取
double
并将其保存到变量d
。 I want to be able to do this an unspecified amount of times.我希望能够以未指定的次数执行此操作。 I use the following code to create a pointer to
d
.我使用以下代码创建一个指向
d
的指针。
double *pd = new double;
pd = &d;
I then push this pointer into a constructed stack (list) class.然后我将此指针推入构造的堆栈(列表)类。 But whenever I push more than one double it changes all of them (the pointer is the same).
但是每当我推动超过一倍时,它都会改变所有这些(指针是相同的)。
Ex.前任。 push 2 and get an array [2].
按 2 并得到一个数组 [2]。 push 3 and get array [3, 3] instead of [3, 2].
推 3 并得到数组 [3, 3] 而不是 [3, 2]。
Why are you using pointers at all?你为什么要使用指针?
std::vector<double> v;
double d;
while (std::cin >> d)
v.push_back(d);
Or as chris points out:或者正如克里斯指出的那样:
std::copy(std::istream_iterator<double>(std::cin),
std::istream_iterator<double>(),
std::back_inserter(v));
*pd = d
instead of代替
pd = &d;
What you do is:你要做的是:
double d
variable on stackdouble d
变量pd
variablepd
变量中pd
on listpd
on list 保存This means you have list of addresses to variable d
(every single object on list is pointer to d
variable).这意味着您有变量
d
的地址列表(列表中的每个对象都是指向d
变量的指针)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.