문제

I'm trying to initialize a vector iterator so I can search for an element in a vector. However, when I try to initialize it I get a conversion error. Not sure what the problem is, any help?

int solution(int K, const vector<int> &A) {
    int count=0,size,comp=0;
    //int *index;
    vector<int>::iterator index;

    size = A.size();

    for(int i=0;i<size;i++){
        comp = K-A[i];
        index = find(A.begin(),A.end(),comp);
        cout <<"index: " << *index << endl;
        if(*index + A[i] == K)
            count++;
    }
    return count;
}

The error is

candidate function (the implicit copy assignment operator) not viable: no known conversion from
      '__normal_iterator<const int *, [...]>' to 'const __normal_iterator<int *, [...]>' for 1st argument
    class __normal_iterator
도움이 되었습니까?

해결책

You should write this one

vector<int>::const_iterator index;

since A is const vector whose elements cannot be mutated. And const_iterator used to read only but cannot to modify the element it points to.

다른 팁

The STL iterators are like a generalization of pointers, and follow the same rules regarding const data. STL iterators need to reflect the constantness of the container in question. The type that you are looking for is std::vector::const_iterator.

Like const int* and int*, you can convert an iterator to a const_interator, but not a const_iterator to an iterator.

If you are using C++11, then you can just use the auto specifier and let the compiler deal with the type inference.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top