0

I have an array in python, which is declared as follow:

u[time][space]

My code in Python's for loop requires me to do the following:

for n in range(0,10):
    u[n][:] = 1

This colon indicates the whole range of my [space].
Now, how would I go about to use the colon (:) to indicate the whole range when doing for loop in c++?

Thanks

3
  • Use 2 loops in C++ instead of one (like in Python). Commented May 4, 2017 at 14:54
  • You might use something like auto v = std::vector<std::vector<int>>(time, std::vector<int>(space, 1)); instead. Commented May 4, 2017 at 14:58
  • this question is pretty vague. what exactly are you trying to do? if you're just trying to assign vectors a value of 1, look at constructor 4 -- otherwise, manipulating vectors takes two loops because it doesn't have slicing syntax on lists Commented May 4, 2017 at 14:58

5 Answers 5

3
for(auto& inner : u)
    std::fill(inner.begin(), inner.end(), 1);
Sign up to request clarification or add additional context in comments.

Comments

0

Use two loops as suggested. Something like:

int n, s;
for(n=0; n<10; n++){
   for(s=0; s<space; s++){
      u[n][s] = 1;
   }
}

should work.

Comments

0

C++ does not have an equivalent to

for n in range(0,10):
    u[n][:] = 1

You are going to have to write the loop that u[n][:] = 1 represents. Fortunately with ranged based for loops it is pretty trivial. That would look like

int foo[3][3];
for (auto& row : foo)
    for (auto& col : row)
        col = 1;

Comments

0

I don't remember a quick way to do it in C++. I'm afraid you'd have to loop in each table.

This would look like this (admitting that space is a known integer):

for (int i = 0; i < 10; i++)
    for (int j = 0; j < space; j++)
        u[i][j] = 1;

Comments

-1

You're going to have to use two loops. Modern C++ has some tricks up its sleeve to make initializing these loops simple, but here is a basic C example that will work anywhere:

#define TIME_MAX 100
#define SPACE_MAX 350

int u[TIME_MAX][SPACE_MAX];
int i, j;

for (i = 0; i < TIME_MAX; i++)
    for (j = 0; j < SPACE_MAX; j++)
        u[i][j] = 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.