使用std::vector<char>代替char[]数组

在以前老一辈技术人员都喜欢使用new char[]来进行动态分配字符串数组,这种情况很容易忘记使用delete进行配对导致内存泄漏。为解决此问题,我们可以使用std::vector<char>容器(内存连续)来代替动态分配数组的功能,以下代码展示了vector的使用:

template<typename _Tp,_Tp value>
_Tp to_value(_Tp c)
{
    return value;
}

int main()
{

    std::vector<char> pBuf(100,'1');    //分配100个字符,并初始化为'1'
    cout << "data:" << &pBuf.front() <<endl;   //&pBuf.front()为得到字符数组的地址
    transform(pBuf.begin(),pBuf.end(),pBuf.begin(),to_value<char,0>);   //重置vector数组为空
    cout << "data1:" << &pBuf.front() <<endl;

}

猜你喜欢

转载自blog.csdn.net/ancktion/article/details/81134517