Home > front end >  Why I could not assign value and display element of list?
Why I could not assign value and display element of list?

Time:12-01

int Square(int lenght)
{
std::vector < int > square(lenght);
for(int counter :square)
    square[counter] = counter * counter ;

for(int counter : square){
    printf("%d",square[counter]);
        cout<<""<<endl;
}

Hi there

As you see I have basis code block in cpp . I try to make Range-loop using for loop always taking "0" from terminal awkward.How can I fill out with square values ? What is the problem technically or What would you advice for me at similiar case?

CodePudding user response:

for(int counter :square)

Here you are using range based for loop. What this means is that in every step counter will go through elements instead of indices. If you want to use indices you should instead use a standard for loop:

for (int counter = 0; counter < length;   counter)

CodePudding user response:

You can't use the range loop like that. The range loop loops through every element in the vector and assigns the left variable in the loop the value of the element. E.g. your output code should look like this:

for(auto const& val: square){
    std::cout<<val<<std::endl;
}
  • Related