C++ 谁将结构存储在堆栈中(STL)

C++ Who storing the struct in the stack (STL)

我有这样的问题: C++: Storing structs in a stack

我的代码:

#include <stdio.h>
#include <stack>
#include <iostream>
#include <string>
using namespace std;

struct adresse{

    string info;
};

int main(){

    string eingabe;
    stack<adresse> Stack1;

    cout << "Bitte Ausdruck eingeben: " << endl;
    getline( cin, eingabe);

    adresse* temp;
    temp = new adresse;
    temp->info = eingabe[0];
    Stack1.push(temp);

    return 0;  
}

错误是:

reference to type 'const value_type'(aka 'const adresse') could not bind to an 
lvalue of type 'adresse *'Stack1.push(temp);

怎么了?

谢谢

汤米

您声明您的堆栈包含 adresses,但正试图推送 adresse.

地址

首先要做你正在做的事情,你需要一个像这样的堆栈,

stack<adresse*> Stack1;

如果你想使用你自己的堆栈,那么像这样推送它

Stack1.push(*temp);

当写 Stack1.push(temp) 时,temp 是一个 adresse *,而 Stack1.push 需要一个 adresse const & 参数。

这就是编译器试图告诉您的内容。

要解决此问题,只是不要将 temp 存储为指向对象的指针,而是直接存储为对象。

adresse temp;
temp.info = eingabe;
Stack1.push(temp); // maybe `std::move(temp)` instead of `temp`

而不是 new 和你用 temp 做的事情。 new 这里不需要。 [0] 不是必需的。不需要指针。

一般来说,new就是"create a copy of this whose lifetime I will manage manually, and whose access is slower"。它 returns 指向您 new 编辑的内容的指针。如果您不需要对所创建内容的生命周期进行细粒度控制,请改为在堆栈上创建它。

在一些现代 C++ 编码风格中,不鼓励在特定低级资源管理函数之外对 new 的所有调用(如 make_sharedmake_uniqueboost::variant 或类似)。但是你还是需要理解指针。

您创建了一个指向某些数据的指针,并试图将其存储在需要某些数据值的容器中。容器想要一个对它要复制的现有数据块的引用:你给它一个指向某些数据的指针。它们不是同一种类型,所以编译器给了你一个错误,说没有办法自动从一种类型转换为另一种类型。

你有一些问题。

首先你的header<stdio.h>Cheader,在C++中使用<cstdio>.

接下来您将创建一个指向 object 的指针并尝试将该指针压入堆栈。不用做指针,直接定义object即可。

最后使用 eingabe[0] 只给出存储在 eingabe 中的单词的第一个字母。

尝试以下操作:

//#include <stdio.h> // not this in C++
#include <cstdio> // use this instead
#include <stack>
#include <iostream>
#include <string>
using namespace std;

struct adresse
{

    string info;
};

int main()
{

    string eingabe;
    stack<adresse> Stack1;

    cout << "Bitte Ausdruck eingeben: " << endl;
    getline(cin, eingabe);

    // no need to make pointers just use
    // adresse as if it were built in
    adresse temp;
    temp.info = eingabe; // [0] will only give you the first letter
    Stack1.push(temp);

    return 0;
}