使用 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
功能。
看看std::vector
提供的所有成员:你真的需要Cell
来暴露,比如说,allocator_type
、back
、pop_back
、operator>=
或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 之前建立的最佳实践还需要或至少鼓励您将非成员函数添加到类中size
和empty
,以实现与std::empty
和std::size
函数的兼容性:
bool empty(Cell const& cell)
{
return cell.size() == 0;
}
int size(Cell const& cell)
{
return cell.size();
}
相关文章:
- 头文件可以在主类中运行.这怎么可能?
- 怎么可能只让设备使用 pjsua2 捕获或播放
- std::lock_guard 怎么可能比 std::mutex::lock() 更快?
- 怎么可能写 f( *this, std::forward<Args>(args)... ) 而 f 只用 F f 声明;
- 在QT C++编辑Qtable模型数据时,我需要得到一个小盒子,我需要显示编辑文本,这怎么可能?
- 在给定相同的输入的情况下,某些代码怎么可能花费更多时间来运行,这似乎只是因为它处于循环中?
- 答案怎么可能是433?
- 八进制文字怎么可能是负数?
- 我们可以在整数类型的双指针中分配2D整数数组的地址吗?怎么可能
- 我怎么可能从尚未定义某些成员方法的类创建实例?(C++)
- 使用 stl 迭代器封装向量是否很好?如果是?怎么可能呢?
- 几个比较怎么可能比一些计算慢
- 我的 Cuda 矢量怎么可能在填充后是空的
- 怎么可能有两个同名的变量——一个是全局变量,另一个是局部变量
- 奇怪的交叉播.这怎么可能
- 一个变量怎么可能既是constexpr又不是constexpr
- 如果方法私有,是否可以从 main 调用该方法?如果不是,怎么可能
- ANSI到Unicode或向后转换:怎么可能?
- 字符 * 名称 = "Duncan" 怎么可能 ;如果指针只能保存地址,是否有效?
- 如果-怎么可能这样做