[英]Expose access and assignment operator from private vector
I am working in a code in C++ where a class that I created stores a vector of boost/dynamic_bitset as a private field. 我正在使用C ++中的代码进行工作,其中我创建的类将boost / dynamic_bitset的向量存储为私有字段。 I need to be able to access and modify any position in the vector to do bitset operations (&, |, ^, ...).
我需要能够访问和修改向量中的任何位置以进行位集操作(&,|,^,...)。
It's possible to expose the vector assignment ( = ) and access( [] ) operators without having to reimplement them? 可以公开向量分配( = )和access( [] )运算符,而不必重新实现它们吗? Just like I did with iterators.
就像我对迭代器所做的一样。
Here is the header: 这是标题:
class graph{
typedef vector<boost::dynamic_bitset<>> tgraph;
node person;
tgraph gg;
public:
graph();
graph(const uint person, const uint max_days, const uint max_nodes);
void add_encounter_index(const node);
void add_encounter_index(const node, const node, const node);
void dump(ofstream& f, const vector<encounter>&);
// iterators
using iterator = tgraph::iterator;
// using pointer = tgraph::value_type;
using reference = tgraph::reference;
// using value_type = tgraph::value_type;
using const_iterator = tgraph::const_iterator;
using const_reference = tgraph::const_reference;
iterator begin() { return gg.begin(); }
iterator end() { return gg.end(); }
const_iterator begin() const { return gg.begin(); }
const_iterator end() const { return gg.end(); }
const_iterator cbegin() const { return gg.cbegin(); }
const_iterator cend() const { return gg.cend(); }
};
You can overload operator[]
for graph
so that it resolves to a reference to the vector element, eg: 您可以为
graph
重载operator[]
,以便将其解析为对向量元素的引用,例如:
// Inline member function
auto& operator[](size_t index)
{
return gg[i];
}
(In older versions of C++ you'll need to specify the dynamic_bitset
type instead of auto
). (在较旧的C ++版本中,您需要指定
dynamic_bitset
类型而不是auto
)。 This enables you to use: 这使您可以使用:
graph1[i] = dynamic_bitset<>(size);
and other such statements. 和其他此类陈述。 You could overload
operator=
, but that applies to the usage graph1 =
, and it can get confusing to overload this operator to do something different to its default behaviour. 您可以重载
operator=
,但这适用于用法graph1 =
,并且使该运算符重载以执行与其默认行为不同的操作可能会造成混淆。 So if just the operator[]
overload suits your requirements then I'd recommend just doing that one. 因此,如果只是
operator[]
重载满足您的要求,那么我建议您只做一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.