Access index in range-for loop

后端 未结 6 491
忘了有多久
忘了有多久 2020-12-24 11:44

I have a vector of objects and am iterating through it using a range-for loop. I am using it to print a function from the object, like this:

vector

        
6条回答
  •  感动是毒
    2020-12-24 12:20

    It's pretty simple honestly, just got to figure out that you can subtract addresses :)

    &i will reference the address in memory, and it will increment by 4 from index to index because it's hold a integer from the defined vector type. Now &values[0] references the first point, when you subtract the 2 addresses, the difference between the two will be 0,4,8,12 respectfully, but in reality its subtracting the size of the integer type which is usually 4 bytes. So in correspondence 0 = 0th int,4 = 1st int, 8 = 2nd int, 12 = 3rd int

    Here it is in a vector

    vector values = {10,30,9,8};
    
    for(auto &i: values) {
    
    cout << "index: " <<  &i  - &values[0]; 
    cout << "\tvalue: " << i << endl;
    
    }
    

    Here it is for a regular array, pretty much the same thing

    int values[]= {10,30,9,8};
    
    for(auto &i: values) {
    
    cout << "index: " <<  &i  - &values[0];
    cout << "\tvalue: " << i << endl;
    
    }
    

    Note this is for C++11, if you're using g++, remember to use -std=c++11 parameter for compiling

提交回复
热议问题