質問

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.

I am wondering how to fix this. I tried "if(nameofdeque.at(i) >= nameofdeque.at(i+1){" but to no avail.

Any help is greatly appreciated, Thanks!

役に立ちましたか?

解決

operator[] takes size_t i.e. an index but you're passing an iterator to it. 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.

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;
 }

他のヒント

Iterator is not an index of deque, you use *i to access the member it points to.

In you code i is an iterator, not an index (integer). operator[] requires index (integer) as an argument.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top