Skipping in Range-based for based on 'index'?

后端 未结 7 1381
一向
一向 2021-01-02 01:10

Is there a way to access the iterator (suppose there\'s no loop index..?) in a C++11 range-based for loop?

Often we need to do something special with the fi

7条回答
  •  甜味超标
    2021-01-02 02:10

    How about using a simple for loop with iteratos:

    for(auto it = container.begin(); it != container.end(); it++)
    {
        if(it == container.begin())
        {
            //do stuff for first
        }
        else
        {
            //do default stuff
        }
    }
    

    It's not range based, but it's functional. In case you may still want to use the range loop:

    int counter = 0;
    for(auto &data: container)
    {
        if(counter == 0)
        {
            //do stuff for first
        }
        else
        {
            //do default stuff
        }
        counter++;
    }
    

提交回复
热议问题