2

In python if I have some iterable can I do something like this:

v = v[n:k] // 
for i in v[3:]:
     "do something"

and now in C++ I want to this:

vector<int> v = {1,2,3,4,5,6,7,8}
v = v[3:5]; 

Or something like this:

for(auto n: v[2:end])
       "do something";

I tried to find the syntax for this problem but haven't found anything yet.

cigien
  • 57,834
  • 11
  • 73
  • 112
TheFlash
  • 25
  • 5
  • 2
    Instead of describing the Python syntax, describe what you want the result to be. – Pete Becker Jul 15 '21 at 23:47
  • You could do something like: `for(auto i : std::vector(v.begin() + 2, v.end()))` – Ranoiaetep Jul 15 '21 at 23:52
  • 2
    I don't know python, but if you want to look at a specific range of elements in your array you can use iterators and increment them by n or k. ```std::vector v = {0, 1, 2, 3, 4, 5, 6};``` then you can, say, loop through only elements 2 to 4. ```for(auto it = v.begin() + 2; it != v.begin() + 4; ++it) {}``` – NeonFire Jul 15 '21 at 23:52
  • Python is not C++. Don't use Python techniques when writing C++ code, otherwise you will just have C++ code that is buggy, inefficient, has memory leaks, or will just look plain weird to a C++ programmer. – PaulMcKenzie Jul 16 '21 at 00:27

1 Answers1

6

Prior to C++20, you can always do:

for(auto i : std::vector(v.begin() + 2, v.begin() + 5))
{
    foo(i);
}

However it is not recommended as it creates a new vector by copying all elements needed. It would be better to just do a iterator based for loop:

for(auto it = v.begin() + 2; it != v.begin() + 5; ++it) 
{
    foo(*it);
}
// or
for(size_t index = 2; index != 5; ++index) 
{
    foo(v[index]);
}

With C++20 introducing span, you can do:

for(auto i : std::span(v.begin() + 2, v.begin() + 5))
{
    foo(i);
}

It uses the same syntax as the first one, without the need of copying elements.


Also I believe std::vector(&v[2], &v[5]) and std::span(&v[2], &v[5]) are also valid, but I need someone to confirm it.

Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39