2

When working with arrays in C++, is there a simple way to access multiple indices of an array at once à la Python's :?

E.g. I have an array x of length 100. If I wanted the first 50 values of this array in Python I could write x[0:50]. In C++ is there an easier way to access this same portion of the array other than x[0,1,2,...,49]?

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
kl0f
  • 21
  • 3
  • Depends on what you do with that slice. I'd lean towards a pair of pointers. – Quentin Jan 31 '18 at 17:44
  • other than x[0,1,2,...,49] ? i guess you meant `x[0], x[1], x[2]...` for single elements. The way to access a portion of an array is via iterators – 463035818_is_not_an_ai Jan 31 '18 at 17:44
  • if array elements are primitive type, `std::memcpy` will be a good choice. – Ratul Sharker Jan 31 '18 at 17:46
  • @Quentin I want to assign/update that portion of the array. – kl0f Jan 31 '18 at 17:49
  • It kinda also depends on whether you are talking about raw C-style arrays, or `std::array`. (And `std::vector` is another class to consider). I would *recommend* using those classes, and the answers here might be helpful. https://stackoverflow.com/questions/11102029/how-can-i-copy-a-part-of-an-array-to-another-array-in-c If you wanted to *modify* the elements in question in the original array, you could consider making it an array of int references or pointers. Or just have the function doing the modifying take `begin` and `end` parameters. – zzxyz Jan 31 '18 at 17:53
  • Boost provides an "iterator range" pseudo-container. e.g. `for (auto& elt : boost::make_iterator_range(x.begin(), x.begin() + 50)) { ... }` – Daniel Schepler Jan 31 '18 at 18:06

2 Answers2

1

The closest you can come is probably using iterators. In <algorithm> you can find a bunch of functions that act on an iterator range, for example:

#include <algorithm>

int x[100];
int new_value = 1;
std::fill(std::begin(x), std::begin(x) + 50, new_value);

This would change the values in the range to new_value. Other functions in <algorithm> can copy a range (std::copy), apply a function to elements in a range (std::transform), etc.

If you are using this, be aware that std::begin and std::end only work with arrays, not with pointers! Safer and easier would be to use containers like std::vector.

Jonathon Vandezande
  • 2,446
  • 3
  • 22
  • 31
rain city
  • 227
  • 1
  • 7
0

you can do something like below

int main()
{
  int myints[]={10,20,30,40,50,60,70};
  array<int,5> mysubints;

  std::copy(myints, myints+5, mysubints.begin());

  for (auto it = mysubints.begin(); it!=mysubints.end(); ++it)
        std::cout << ' ' << *it;

  std::cout << '\n';
}

you can also use vector instead of array data type

Maddy
  • 774
  • 5
  • 14