will range based for loop in c++ preserve the index order

后端 未结 3 1455
别那么骄傲
别那么骄傲 2020-12-30 23:58

in c++11, if I use a range based for loop on vector, will it guarantee the iterating order? say, will the following code blocks are guaranteed for same output?



        
3条回答
  •  长发绾君心
    2020-12-31 00:47

    Yes and no (It depends on the container in use):

    • The range based for is a loop like for(iterator pos = range.begin(); pos != range.end(); ++pos) { /* with a range variable = *pos */ ... }
    • An operator [] might do something different (eg. a std::map operator does a lookup on the key and create a new entry, if the key does not exist)

    Example:

    #include 
    #include 
    
    int main()
    {
        typedef std::map map;
        map m = { { 0, 0 }, { 2, 2 }, { 4, 4 } };
        for(const auto& e : m) {
            std::cout << e.first << " ";
        }
        std::cout << std::endl;
        for(map::size_type i = 0; i < m.size(); ++i) {
            std::cout << m[i] << " ";
        }
        std::cout << std::endl;
        return 0;
    }
    

    The result is:

    0 2 4 
    0 0 2 0 4 
    

    (The second result might be a good shot in the own foot or even intended)

提交回复
热议问题