我正在使用for循环来访问和打印向量中的值(v)。 for循环使用从v.beginning开始并在v.end之前结束的随机访问迭代器变量。
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> v;
/* create initializer list */
auto inList = {1, 2, 3, 4, 5};
//EDIT
//Works
vector<int> vect1;
vect1.assign(5,100);
for(auto it=vect1.begin(); it<vect1.end();it++){
cout<<*it<<endl;
}
//Works
for(auto it=v.begin(); it!=v.end();it++){
cout<<*it<<endl;
}
return 0;
// Edit: seems to work now.
for(auto it=v.begin(); it<v.end();it++){
cout<<*it<<endl;
}
// Doesn't Work (ERROR MARKERS Correspond to the following loop)
for(int it=v.begin(); it!=v.end();it++){
cout<<*it<<endl;
}
return 0;
}
观察: 当我尝试将类型从“auto”更改为“int”时,我收到以下错误:
- mismatched types 'const std::reverse_iterator<_Iterator>' and 'int'
- mismatched types 'const std::fpos<_StateT>' and 'int'
- mismatched types 'const std::pair<_T1, _T2>' and 'int'
- cannot convert 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' to 'int' in initialization
- no match for 'operator!=' (operand types are 'int' and 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*,
std::vector<int> >}')
- mismatched types 'const __gnu_cxx::__normal_iterator<_IteratorL, _Container>' and 'int'
- mismatched types 'const __gnu_cxx::__normal_iterator<_Iterator, _Container>' and 'int'
- mismatched types 'const std::vector<_Tp, _Alloc>' and 'int'
- mismatched types 'const __gnu_cxx::new_allocator<_Tp>' and 'int'
- mismatched types 'const std::istreambuf_iterator<_CharT, _Traits>' and 'int'
- mismatched types 'const _CharT*' and 'int'
- mismatched types 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'int'
- mismatched types 'const std::allocator<_CharT>' and 'int'
- mismatched types 'const std::move_iterator<_Iterator>' and 'int'
此外,当我恢复将'it'变量的类型更改为'auto'并将for循环的停止条件从'!='更改为&lt;然后它不起作用,虽然cpp引用说“&lt;”运营商支持它。
问题
1)为什么我的迭代器变量必须为.begin()和.end()函数输入'auto'?
2)为什么我不能使用'&lt;'具有迭代器变量的逻辑运算符?
答案 0 :(得分:2)
如果你不想,你不必使用auto
,但你当然可以。
std::vector<int>::begin()
和std::vector<int>::end()
返回的类型为std:vector<int>::iterator
(或std:vector<int>::const_iterator
,具体取决于具体情况),不是int
。你也可以写这个:
for(vector<int>::iterator it=vect1.begin(); it<vect1.end();it++){
cout<<*it<<endl;
}
或
for(vector<int>::const_iterator it=vect1.begin(); it<vect1.end();it++){
cout<<*it<<endl;
}
在任何一种情况下,您都不想修改矢量的内容。关于你的例子:
第一个for循环很好并且有效。我之前从未见过有人使用<
运算符,而是!=
。
第二个for循环也可以,但不执行任何操作,因为v
为空。
第三个for循环是无意义的,正如所指出的,迭代器由begin()
和end()
返回,而不是整数。要访问迭代器指向的数据,您需要使用*
运算符取消引用它,就像输出一样。
希望这有帮助。
修改:还有一件事。在C ++中,建议使用++it
而不是it++
,通常用于for循环中的所有增量。
这是一个简短的解释: