简体   繁体   English

push_back到向量时的运行时错误

[英]Runtime error when push_back to a vector

#include <iostream>
#include <utility>
#include <vector>
using namespace std;

int main() {
    vector<pair<int, int>*> *v;
    pair<int, int> *x = new pair<int, int>();
    cin >> x->first >> x->second;
    v->push_back(x);
    cout << v->size() << endl;
    return 0;
}

Why does this code get run-time error? 为什么此代码会出现运行时错误? I dont understand. 我不明白。 All I do is appending a pair pointer to a vector of pair pointer. 我要做的就是将对指针附加到对指针的向量上。

First of all: Vector definition should be (this resolves the run-time error): 首先:矢量定义应该是(这解决了运行时错误):

vector<pair<int, int>*> v;

Second, you don't release the memory of the new pair. 其次,您不会释放新对的内存。 This will solve that issue too: 这也将解决该问题:

vector<pair<int, int>> v;
pair<int, int> x{ 0,0 };

A vector of pairs, rather than a vector of pair-pointers. 向量对,而不是向量对指针。 On the other hand: If it necessary to use a vector of pointers, smart pointers is a better choice. 另一方面:如果有必要使用指针向量,则智能指针是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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