Reputation: 21
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]
?
Upvotes: 2
Views: 1846
Reputation: 217
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
.
Upvotes: 1
Reputation: 774
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
Upvotes: 0