简体   繁体   English

C ++,我想知道如何分配内存向量 <int, int> &gt; *

[英]C++, I want to know how to allocate memory vector< pair<int, int> > *

I have an error _Has_unused_capacity() vector... I don't know how to allocate dynamic memory 我有一个错误_Has_unused_capacity()矢量...我不知道如何分配动态内存

I try to push_back, but the error occurred 我尝试push_back,但是发生了错误

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

void Some_Function(){
   int m=3;
   int idx1=1;
   int idx2=2;
   int idx3=3;

   for(int i = 0; i<m; i++) {
       v[idx1].push_back(make_pair(idx2, idx3));      
       v[idx2].push_back(make_pair(idx1, idx3));
   }
}

You have a poiter to a vector which points to nowhere. 你有一个指向任何地方的向量的虚弱点。 Either allocate memory for your vector ( not recommended though) or don't use a pointer. 为您的向量分配内存(虽然不建议这样做)或不使用指针。

vector< pair<int, int> > * v = new vector<pair<int, int>>[2];
V[idx].push_back(make_pair(idx2, idx3));

Don't forget to delete your vector when you are done with that. 完成操作后,不要忘记删除向量。

delete [] v;

The better way is using smart pointers, here is an example with shared_ptr : 更好的方法是使用智能指针,这是shared_ptr的示例:

#include <iostream>

#include <vector>
#include <memory>

using namespace std;
using vecPair = vector<pair<int, int>>;

// deallocator for an array of vectors
void deleter(vecPair* x)
{
    delete[] x;
}

int main() {
    shared_ptr<vecPair> v;
    v.reset(new vecPair[2], deleter);
    int a = 1;
    int b = 2;
    int c = 3;
    int d = 4;
    v.get()[0].push_back(make_pair(a, b));
    v.get()[1].push_back(make_pair(c, d));
}

At first, I don't recommend you to use pointer to container. 首先,我不建议您使用指向容器的指针。

Also, the element is pointer may cause memory leak. 同样,该元素是指针可能会导致内存泄漏。

But, if must. 但是,如果必须的话。 you can use std::vector<std::vector<std::pair<int, int>> 您可以使用std::vector<std::vector<std::pair<int, int>>

OR, auto vec = std::make_shared<std::vector<std::vector<std::pair<int, int>>>() 或, auto vec = std::make_shared<std::vector<std::vector<std::pair<int, int>>>()

use smart pointer may manage memory by itself. 使用智能指针可以自己管理内存。 std::make_shared has been support since C++14 从C ++ 14开始就一直支持std::make_shared

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

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