【问题标题】:Private vector in class类中的私有向量
【发布时间】:2020-10-03 19:13:58
【问题描述】:
    class MyStrValArray
{
private:
    vector<char> p;
public:
    void init(const int n);
    void clear();
    unsigned capacity();
    unsigned size();
};

我想有一个向量作为私有类成员,在公共部分,我想声明向量的大小(const int n)。有没有办法做到这一点? 而我想使用向量的原因是,我需要获取内存的大小/容量,调整大小或删除内存的第 n 个元素。在这种情况下使用向量是否正确?

【问题讨论】:

  • 您的问题到底是什么?实现方法?
  • 如何在类的公共部分声明向量的大小?
  • 更改尺寸使用p.resize(&lt;size&gt;),反转尺寸使用p.reserve(&lt;size&gt;)
  • 我认为您正在尝试重新实现std::string

标签: c++ vector


【解决方案1】:

如果您尝试实现自定义字符串实现,那么使用“char * data”更为合适。

否则你可以像这样使用向量:

#include <iostream>
#include <vector>

using namespace std;

class MyStrValArray
{
private:
    vector<char> p;
public:
    MyStrValArray() {}
    MyStrValArray(const int sz ) : p(sz){}
    void init(const int n)
    {
        p.resize(n);
    }
    void clear()
    {
        p.clear();
    }
    unsigned capacity()
    {
        return p.capacity();
    }
    unsigned size()
    {
        return p.size();
    }


};

int main()
{
    MyStrValArray ma;
    ma.init(4);

    std::cout<<ma.size()<<std::endl;

    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 2021-12-14
    • 2016-07-22
    • 2017-10-31
    • 2014-05-23
    相关资源
    最近更新 更多