使用 stl 迭代器封装向量是一种好习惯吗?如果是?怎么做到的?

Is it good practise to encapsulate a vector using stl iterator? If it is? How could it be done?

我是 C++ 的新手,想为我的向量实现封装。

#pragma once

#include <vector>

using namespace std;

class Cell {
public:
    Cell();
    Cell(const Cell& cell);
    void setVector(vector<int> vector[]);
    vector<int> getVector(void)const;

private:
    vector<int> m_vector;
};

我最近阅读了有关 STL 迭代器的内容,所以我想知道以这种方式实现我的 setVector() 方法是否是一种好的做法?如果是,您能举例说明如何实现吗?

与其公开整个向量,无论是通过引用还是使用迭代器,您应该只公开您实际需要的 std::vector 的那些成员函数。

或者更准确地说:您应该只公开您实际需要的 std::vector 功能

看看所有 members provided by std::vector:你真的需要 Cell 来暴露,比如说,allocator_typebackpop_backoperator>=shrink_to_fit?


实现 实际 封装而不仅仅是表面伪封装的更强大的解决方案是从 Cell 成员函数显式委托给所需的向量成员函数。例如,如果您只需要大小和单个元素访问,那么为什么不直接向 Cell 添加一个 size 成员函数和一个 elementAt 成员函数并将这些函数的实现委托给私有向量?

示例:

#include <vector>

class Cell {
public:
    Cell(std::vector<int> const& vector) : m_vector(vector) {}

    int size() const
    {
        return static_cast<int>(m_vector.size());
    }

    int elementAt(int index) const
    {
        return m_vector[index];
    }

private:
    std::vector<int> m_vector;
};

也许您甚至不需要构造函数中的 std::vector 参数。你可以接受任何你想要的输入并用它初始化私有向量。


顺便说一句,C++17 很可能建立的最佳实践也需要或至少鼓励您将非成员函数 sizeempty 添加到 class,为了实现与std::empty and std::size函数的兼容:

bool empty(Cell const& cell)
{
    return cell.size() == 0;
}

int size(Cell const& cell)
{
    return cell.size();
}