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]?

6
  • Depends on what you do with that slice. I'd lean towards a pair of pointers. Commented Jan 31, 2018 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 Commented Jan 31, 2018 at 17:44
  • if array elements are primitive type, std::memcpy will be a good choice. Commented Jan 31, 2018 at 17:46
  • @Quentin I want to assign/update that portion of the array. Commented Jan 31, 2018 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. stackoverflow.com/questions/11102029/… 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. Commented Jan 31, 2018 at 17:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The question says you need to retrieve first 50 values sort of thing
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

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.