简体   繁体   English

如何在循环 C++ 中创建唯一指针?

[英]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:你要做的是:

  • you have double d variable on stack你在堆栈上有double d变量
  • you create double and save its pointer in pd variable您创建 double 并将其指针保存在pd变量中
  • then you save address to d variable in pd然后将地址保存到 pd 中的 d 变量
  • and then you save address from pd on list然后您将地址从pd 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM