首页 > 解决方案 > 为什么不同的向量元素共享相同的地址?

问题描述

我已经定义了以下类。

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->childInds 中的两个元素具有连续的地址(如预期的那样),而 s 中的两个元素a->isInfluenced似乎共享相同的地址?

更新:

vector<bool>从评论中我了解到,这与与其他vectors之间的区别有关。还有其他vector我应该注意的特殊情况,还是vector<bool>我需要注意的唯一情况?

标签: c++

解决方案


他们没有。好吧,他们确实……

vector<bool>不像其他向量。

a 的元素vector<bool>不能像这样直接访问,因为它们/可能小于一个字节,这是 C++ 中地址的“分辨率”。如此多的位/元素被打包到计算机上的一个内存位置。但这不是你得到这些结果的原因。

你有点观察临时地址。该临时对象是一些代理对象,它提供对集合中单个位的可变访问。

我说“有点”是因为您甚至没有真正接受地址;所说的代理对象有一个operator&在某些实现中为您提供称为“位迭代器”的东西。

这是霍华德·欣南特vector<bool>

同时,在使用 时vector<bool>,忘掉你对向量的了解。


还有其他vector我应该注意的特殊情况,还是vector<bool>我需要注意的唯一情况?

vector<bool>是唯一的一个。


推荐阅读