lundi 3 juin 2019

How to add a user accepted integer (variable distance) to an iterator in C++?

OK, one of those rare occasions when the (rest of) the Internet failed me ! I'm trying to scan through a vector in C++ using iterators, but instead of iterating from beginning to end, or through a fixed slice, like "(v.begin() +7 ) to (v.begin() + 10)" etc, I'm using "cin" to accept the starting index (called LeftEnd or L) and the ending index (RightEnd or R) from the user

I've been stuck at this for over half a day!

The error i get is :

invalid operands of types '' and 'std::vector::difference_type {aka long int}' to binary 'operator+'

OR

error: invalid operands of types '' and 'int' to binary 'operator+'

/*This is only for Context. You may please skip straight to the last 3 lines of the code - the last for loop at the end marked "IMPORTANT BIT" (actually the one line containing the last 'for loop' is the culprit.)*/

struct Marks{
    string exam;
    int Math;
    int Physics;   
};

int main(){

    //some code
    int counter = 1;
    vector <Marks> m;
    vector <Marks> :: iterator it;

    //Just populating the vector. NOT IMPORTANT. Only for some context

    for (it = m.begin(); it!=m.end(); it++){
        it->Math = 10;       // random shit..just fillin' up the vector
        it-> Physics = 10 //
        counter++;
    }
    cout <<"Enter the endpoints of the slice of indices through which you want 
          to change the Math marks " << endl;

    cin >> L >> R; 


   //**IMPORTANT BIT**:-

    vector <Marks> :: iterator mit;

    //PROBLEMATIC LINE FOLLOWS!!!! :-
    for (mit = v.begin() + L-1; mit!= v.begin() + R; mit++) {
        mit->Math += 20; 
    }

//The line containing the last for loop is the one giving the error:-
//"error: invalid operands of types '<unresolved overloaded function type>' //and 'int' to binary 'operator+' "


Kindly help!

Aucun commentaire:

Enregistrer un commentaire