在c ++中实现向量时出现运行时错误

时间:2016-10-26 09:48:36

标签: c++ vector

我正在尝试用c ++实现我自己的vector版本。 到目前为止,我已经做到了这一点。

#include<iostream>
#include<string>

using namespace std;


template<class T>
class vec
{
public:
    T *a;
    int i,N;
    vec(int N=0):N(N)
    {
        i=-1;
        a=(T *)malloc(N*sizeof(T));
    }
    void push_back(const T& t);
    T at(const int& index) const;
};

template<class T>
void vec<T>::push_back(const T& t)
{
    if(++i==N)
    {
        a=(T *)realloc(a,(++N)*sizeof(T));
    }
    a[i]=t;
}

template<class T>
T vec<T>::at(const int& index) const
{
    return a[index];
}

int main()
{
    vec<string> v;
    v.push_back("2");
    v.push_back("1");
    v.push_back("3");
    cout<<v.at(0)<<endl;
    return 0;
}

但是当我运行它时,我遇到运行时错误 上面代码中的错误在哪里? 我正在使用c ++和visual studio来运行。

1 个答案:

答案 0 :(得分:0)

在这种情况下,您需要使用展示位置。

类似的东西:

// Allocate memory
void* mem = malloc(sizeof(std::string));

// Call constructor via placement new on already allocated memory
std::string* ptr = new (mem) std::string();

但是,您必须为此内存显式调用析构函数

ptr->~std::string();
总的来说 - 这不是实现你想要的好方法。使用通常的新\删除操作符并在重新分配时复制内部数据(如何在STL向量中完成)更方便