[英]Error in an iterator for a deque
int CardDeck::inOrder(){
deque<int>::const_iterator i;
for (i = nameofdeque.begin(); i != nameofdeque.end(); ++i){
if (nameofdeque[i] >= nameofdeque[i+1]){
return 0;
}
}
return 1;
}
This code gives an error on the 4th line saying "CardDeck.cpp:37: error: expected type-specifier before '[' token CardDeck.cpp:37:: Too many arguments. 这段代码在第四行给出了一个错误,说“ CardDeck.cpp:37:错误:'['令牌CardDeck.cpp:37 :::之前的预期类型说明符”。
I am wondering how to fix this. 我想知道如何解决此问题。 I tried "if(nameofdeque.at(i) >= nameofdeque.at(i+1){" but to no avail. 我试过“ if(nameofdeque.at(i)> = nameofdeque.at(i + 1){”,但无济于事。
Any help is greatly appreciated, Thanks! 任何帮助,不胜感激,谢谢!
迭代器不是双端队列的索引,您可以使用*i
访问它所指向的成员。
In you code i
is an iterator, not an index (integer). 在您的代码中, i
是一个迭代器,而不是索引(整数)。 operator[]
requires index (integer) as an argument. operator[]
需要索引(整数)作为参数。
operator[]
takes size_t
ie an index but you're passing an iterator to it. operator[]
采用size_t
即索引,但您要将迭代器传递给它。 If you want to do it with iterators then change the 4th line to this 如果要使用迭代器执行此操作,则将第四行更改为此
if (*i >= *(i+1)) {
To avoid such confusion, an iterator is usually named iter
instead of the usual identifier used for a loop index or subscript, i
. 为了避免这种混淆,通常将迭代器命名为iter
而不是用于循环索引或下标i
的常用标识符。
If you really want to do this without iterators but with index, then you could change the function to 如果您确实想在没有迭代器但有索引的情况下执行此操作,则可以将函数更改为
int CardDeck::inOrder() {
for (size_t i = 1u; i < nameofdeque.size(); ++i) {
if (nameofdeque[i - 1] >= nameofdeque[i]) { // you cannot do this for the first element, hence the loop's variable starts at 1 to offset this
return 0;
}
}
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.