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


i new c++ , implement encapsulation vector.

#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; }; 

i read stl iterators, know if practice implement setvector() method way? if is, give me examples on how done?

instead of exposing whole vector, via reference or iterators, should expose member functions of std::vector need.

or more precisely: should expose functionality of std::vector need.

look @ members provided std::vector: need cell expose, say, allocator_type, back, pop_back, operator>= or shrink_to_fit?


a more robust solution achieves actual encapsulation , not superficial pseudo-encapsulation explicitly delegate required vector member functions cell member functions. example, if need size , individual element access, why not add size member function , elementat member function cell , have implementations of functions delegate private vector?

example:

#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; }; 

perhaps not need std::vector parameter in constructor. can take input want , initialise private vector it.


as aside, best practices established c++17 require or @ least encourage add non-member functions size , empty class, in order achieve compatibility std::empty , std::size functions:

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

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -