繁体   English   中英

在C ++中实现矢量时发生运行时错误

[英]Runtime error while implementing vector in c++

我正在尝试在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来运行。

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

像这样的东西:

// 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();

总体而言-这并不是实现所需目标的好方法。 使用常规的new \\ delete运算符并在重新分配时复制内部数据(在STL向量中如何完成)更方便。

暂无
暂无

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

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