c++ - 为什么不同的向量元素共享相同的地址?
问题描述
我已经定义了以下类。
class STTreeNode
{
public:
int ind;
int parentInd;
std::vector<int> childInds;
int numTrain;
std::vector<bool> isInfluenced;
STTreeNode(int ind, int parentInd, int numTrain);
};
STTreeNode::STTreeNode(int ind, int parentInd, int numTrain) {
this->ind = ind;
this->parentInd = parentInd;
this->numTrain = numTrain;
}
我运行了以下代码片段。
STTreeNode *a = new STTreeNode(3, 4, 5);
a->childInds.push_back(20);
a->childInds.push_back(30);
a->isInfluenced.push_back(true);
a->isInfluenced.push_back(false);
for (int i = 0; i < a->childInds.size(); i++)
std::cout << &(a->childInds[i]) << " ";
std::cout << std::endl;
for (int i = 0; i < a->isInfluenced.size(); i++)
std::cout << &(a->isInfluenced[i]) << " ";
std::cout << std::endl;
输出是
0000020351C18520 0000020351C18524
00000083540FFC60 00000083540FFC60
我对此感到非常困惑。为什么a->childInd
s 中的两个元素具有连续的地址(如预期的那样),而 s 中的两个元素a->isInfluenced
似乎共享相同的地址?
更新:
vector<bool>
从评论中我了解到,这与与其他vector
s之间的区别有关。还有其他vector
我应该注意的特殊情况,还是vector<bool>
我需要注意的唯一情况?
解决方案
他们没有。好吧,他们确实……
vector<bool>
不像其他向量。
a 的元素vector<bool>
不能像这样直接访问,因为它们/可能小于一个字节,这是 C++ 中地址的“分辨率”。如此多的位/元素被打包到计算机上的一个内存位置。但这不是你得到这些结果的原因。
你有点观察临时地址。该临时对象是一些代理对象,它提供对集合中单个位的可变访问。
我说“有点”是因为您甚至没有真正接受地址;所说的代理对象有一个operator&
在某些实现中为您提供称为“位迭代器”的东西。
同时,在使用 时vector<bool>
,忘掉你对向量的了解。
还有其他
vector
我应该注意的特殊情况,还是vector<bool>
我需要注意的唯一情况?
vector<bool>
是唯一的一个。
推荐阅读
- python - PATH="/custom/dir:$PATH" 前置而不是附加 - Conda vs Pyenv
- yaml - 单转义的yaml输出?
- javascript - 在 vue.js 中访问 javascript 对象
- c++ - 如何解决此重载错误 (c1) 情况?
- geopandas - 上下文制作奇怪的背景图
- linux - 如何阻止 kuberenetes pod 内的 postgres 进程响应
- django - 使用 as_crispy_form 模板标签更改 help_text 位置
- json - 前端/后端之间的新 Date() 时间戳差异
- windows - 从 Git bash 脚本中发送击键(Windows)
- nginx - 使用 nginx 代理获取 404 的静态文件