0
我有一个函数,我提供了一个指向std :: vector的指针。指向std的访问元素::向量
我想使x =向量[元素],但我收到编译器错误。
我做:
void Function(std::vector<int> *input)
{
int a;
a = *input[0];
}
什么是做到这一点的正确方法? 感谢
我有一个函数,我提供了一个指向std :: vector的指针。指向std的访问元素::向量
我想使x =向量[元素],但我收到编译器错误。
我做:
void Function(std::vector<int> *input)
{
int a;
a = *input[0];
}
什么是做到这一点的正确方法? 感谢
应该是:
void Function(std::vector<int> *input)
{
// note: why split the initialization of a onto a new line?
int a = (*input)[0]; // this deferences the pointer (resulting in)
// a reference to a std::vector<int>), then
// calls operator[] on it, returning an int.
}
否则你有*(input[0])
,这是*(input + 0)
,这是*input
。当然,为什么不只是做:
void Function(std::vector<int>& input)
{
int a = input[0];
}
如果你不修改input
,将其标记为const
:
void Function(const std::vector<int>& input)
{
int a = input[0];
}
你也可以去一个一个语法糖饮食和写a = input->operator[](0)
; - )
好的,谢谢!我从来没有听说过这个 – jmasterx 2010-06-05 21:46:01
感谢您的提示,我从来没有用这种方式使用const关键字! – jmasterx 2010-06-05 21:52:05
没问题。我建议写一本好书,以便你可以正确学习C++;我们在这里有一个列表:http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – GManNickG 2010-06-05 21:53:19