C ++ vector []运算符在at()工作时抛出错误

时间:2017-05-01 19:19:39

标签: c++ vector

我有一个A类,它包含一个向量和一个返回指向这个向量的指针的函数。

std::vector<ALuint> * SoundComponent::getSource()
{
    return &m_Sources;
}

我有另一个B类需要通过调用getSource()函数来修改A类向量中的值。所以我通过这样做获得了向量的指针。

std::vector<ALuint> * sources = m_pSoundComponent[i]->getSource();

m_pSoundComponent是A类的数组。现在让s say for example I want to add 1 to the entries in the vector. For some reason operator [] gives me an error but at`正常工作。所以这里有三件我试过的东西,其中两件有用,但我想知道为什么第一件是错的。

sources[0] += 1; //Does not work
sources[0][0] += 1; //Works ? Not sure why it became a 2D vector.
sources->at(0) += 1; //works

我听说at() r比operator []慢得多,所以我尝试使用operator [],但我不知道为什么它现在是2D矢量。

此外,在A类中,我可以使用sources[0]但没有错误,但sources[0][0]给我一个错误。

1 个答案:

答案 0 :(得分:4)

sources被定义为std::vector<ALuint> *。这意味着sources[0]为您提供了向量,它不会访问向量中的元素。它与(*sources)相同。因此,当您尝试将sources[0] += 1添加到向量而不是向量元素时,1没有意义。

使用sources[0][0]获取向量,然后访问向量的第0个元素。这与(*sources)[0]相同。

sources->at(0)做同样的事情。 ->是指针的成员访问运算符,因此它与(*sources).at(0)

相同

如果您返回引用而不是指针,则可以避免所有这些。你可以改变

std::vector<ALuint> * SoundComponent::getSource()
{
    return &m_Sources;
}

std::vector<ALuint>& SoundComponent::getSource()
{
    return m_Sources;
}

然后允许你使用

std::vector<ALuint>& sources = m_pSoundComponent[i]->getSource();

允许您像往常一样使用sources