使用 stl 迭代器封装向量是否很好?如果是?怎么可能呢?

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

本文关键字:如果 怎么可能 很好 是否 stl 迭代器 封装 向量 使用      更新时间:2023-10-16

我对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功能

看看std::vector提供的所有成员:你真的需要Cell来暴露,比如说,allocator_typebackpop_backoperator>=shrink_to_fit吗?


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

例:

#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,以实现与std::emptystd::size函数的兼容性:

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