Range-for-loops and std::vector

前端 未结 3 1673
我在风中等你
我在风中等你 2020-11-28 10:16

Why does this code work

std::vector intVector(10);
for(auto& i : intVector)
    std::cout << i;

And this doesn\'t?

<
3条回答
  •  我在风中等你
    2020-11-28 11:07

    std::vector does not obey the standard container rules.

    In particular, its operator[] does not return bool&.

    The loop in the invalid code

    #include 
    #include 
    
    int main() {
      std::vector boolVector(10);
      for (auto& i: boolVector)
          std::cout << i;
    }
    

    can be rewritten in any of three ways to iterate through the values:

    1. (read-only)

      for (auto i: boolVector)
          std::cout << i;
      
    2. (read-only, possibly inefficient)

      for (auto const& i: boolVector)  
          std::cout << i;
      
    3. (read/write)

      for (auto&& i: boolVector)
          std::cout << i;
      

    The choice between the first and last is down to whether you need to modify the values in the vector, or just to read them.

提交回复
热议问题