【发布时间】:2020-04-15 03:02:31
【问题描述】:
当我使用int it = v.begin()时,它给了我这个错误:
prog.cpp: In function ‘int findFrequency(std::vector<int>, int)’:
prog.cpp:18:32: error: cannot convert ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’ to ‘int’ in initialization
for(int iterator = v.begin();iterator!=v.end();iterator+
但它与auto it = v.begin() 配合得很好,为什么?
【问题讨论】:
-
auto将找出需要的类型。当您使用auto时,它使it成为std::vector::iterator。std::vector::begin返回std::vector::iterator,而不是int。 -
begin()返回一个迭代器,而不是一个 int -
std::vector<int>::begin()不返回整数类型,因此int it = v.begin()不会编译。auto it = v.begin()会起作用,因为它会推断返回的类型。 -
您可能会将
v.front()与v.begin()混淆。前者将返回向量的第一个元素,而后者从向量的开头返回一个迭代器 -
@chatterjee7 plz,如果您觉得有答案符合您的问题,请接受。如果没有,请向我们提供有关您误解的更多信息。