所以,我有一个 vector ,要么全是整数。我们称此 vector 为 Vect
。我在 main.cpp
和 VectorList.h
中有我的代码,并且无法改变这一事实。在 VectorList.h
中,我的功能之一是:
void insertAtFront( const int & );
现在我遇到了麻烦,我知道我可以使用 std::vector.insert()
函数将整数添加到 vector 的开头。但是,insertAtFront
无法访问 vector 本身,但是,这是 VectorList.h
中唯一的数据成员:
vector< int > *vList
所以,我的问题是如何仅使用此指针 *vList
将值添加到 vector Vect
的开头?
我的第一个想法是这样的:
&vList.insert(&vList.begin(), 1, &value) // with value being the input integer
但这不起作用:/有什么建议吗?
最佳答案
如果您有指向 vector 的指针,则需要使用 ->
运算符。在这种情况下使用 &
运算符将为您提供 vList.begin()
返回值的地址。考虑到您不能在指针上使用 .
运算符,这不会很好地工作。相反,您需要取消引用指针。尝试:
vList->insert(vList->begin(), value);
编辑:我不确定为什么在这种情况下您需要中间参数。省略它应该没问题。我已在此处编写的代码行中这样做。
关于C++ 使用指针修改 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351173/