How to Use For Statements Using C++ Auto

Asked 1 years ago, Updated 1 years ago, 139 views

int * buff = new int[10];

for(auto x : buff?? )
{
    x = 0;
}

I want to initialize all the buffs that were assigned dynamically to zero, buff?Please tell me how to write down. I tried buff[], buff, etc., but there are more errors

c++ for dynamic-allocation auto

2022-09-22 08:08

2 Answers

Object to import elements from range-based for statement must have begin() and end() as an array or member function, or a free function begin() and for that object.

int* buff is not an array, so range-based for statements are not available. Therefore, you should use a different method than a pointer.

First, you can use one of the STL containers, std::vector. The std::vector stores elements in continuous memory space, such as an array, and also creates memory space in dynamic memory. The usage is also similar to the array and includes features that are more convenient than the array.

#include <iostream>
#include <vector>

int main() {
    std::vector<int>buff (10); // Create 10 elements
    for (auto x : buff)
        std::cout << x << std::endl;
    return 0;
}

Second, there is a way to force the pointer to an array. This method is not recommended because incorrectly sized arrays can cause serious problems for the program.

#include <iostream>

int main() {
    typedef int Array[10];
    int* buff = new Array;
    for (auto x : reinterpret_cast<Array&>(buff))
        std::cout << x << std::endl;
    return 0;
}


2022-09-22 08:08

Someone else gave me a wonderful answer, but I need one more thing to initialize the array.

for(int x: buff)
    x=0;

The buff array is not initialized to zero in the following code. The reason is that x is an independent variable, as a function uses, and each time it turns, it is equal to the value of buff.

Then we have to point the value exactly by reference.

for(int& x: buff)
    x=0;

You can initialize each value to zero by writing the code as follows:

However, if the purpose is to initialize, it is easier to use the constructor of std::vector.

vector<int> buff(n, k); //n: array size, k: value you want to initialize


2022-09-22 08:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.