Sort and keep track of elements - c++

Just to know, I'm talking C++ now.
Suppose I have an array A = {4, 1, 5, 2, 3} and sort it in A_sorted = {1, 2, 3, 4, 5}. I would like to keep the following information: where is now element e (from array A) in the sorted array A_sorted? e.g.: element with index 2 in A (5) has now index 4 in A_sorted.
The question is more like: can one use STL to achieve this?

There's no off-the-shelf functionality to achieve this, but there are work-arounds. You can, for example, keep an array of user-defined structs that also contain the original position:
A = { {4,0}, {1,1}, {5,2}, {2,3}, {3,4}}
And then sort this using a custom comparator function that sorts by the value and not the original index.
A_sorted = {{1,1}, {2,3}, {3,4}, {4,0}, {5,2}}

Try this out:
If you want to convert to vector:
int A[] = {4, 1, 5, 2, 3};
int A_sorted [] = {1, 2, 3, 4, 5};
std::vector<int> v(A_sorted, A_sorted + 5);
for (int i=0; i<5; i++)
{
std::vector<int>::iterator low = lower_bound (v.begin(), v.end(), A[i]);
std::cout << "Element: " << A[i] << " is at: " << distance(v.begin(), low) << std::endl;
}
If you want to work on raw array:
int A[] = {4, 1, 5, 2, 3};
int A_sorted [] = {1, 2, 3, 4, 5};
for (int i=0; i<5; i++)
{
int* low = std::lower_bound (&A_sorted[0], &A_sorted[5], A[i]);
cout << "Element: " << A[i] << " is at: " << distance(&A_sorted[0], low) << endl;
}

If you cannot modify what's stored in A, you could create an index array and sort it with a special predicate:
int A[] = {4, 1, 5, 2, 3};
size_t indices[] = {0, 1, 2, 3, 4};
bool sortBefore(size_t i, size_t j) {
return A[i] < A[j];
}
std::sort(indices, indices + 5, sortBefore);
Then, either access sorted_A[i] as A[indices[i]], or re-arrange A according to indices. New position of i-th element of A is std::find(indices, indices+5, i) - indices.

template<class T>
struct ValueWithIndex
{
T Value;
int index;
};
template<class T>
bool operator < (const ValueWithIndex<T>& v1, const ValueWithIndex<T>& v2)
{
return v1.value < v2.value;
}
template<class T> ValueWithIndex<T>
MakeValueWithIndex(const T& value, int index)
{
ValueWithIndex<T> ret;
ret.value = value;
ret.index = index;
return ret;
}
Now sort your container of ValueWithIndex. The information about original indexes will not
be lost.
int main()
{
std::vector<ValueWithIndex<int>> v;
for(int i = 0; i < n; ++i)
{
int value;
std::cin >> value;
v.push_back(MakeValueWithIndex(value, i));
}
std::sort(v.begin(), v.end());
}

Ok, an index normally tells you what the nth sorted element of a vector is. But this is going to do the reverse, thus it will tell you that the nth element in your vector is the mth in sorted order.
This is being done by creating a vector of indices on your non-sorted vector. You can still create a sorted copy or an index, of course.
We start off with a predicate for which a < b if v[a] < v[b]
template< typename T >
class PredByIndex
{
private:
std::vector< T > const & theColl;
public:
PredByIndex( std::vector<T> const& coll ) : theColl( coll )
{
}
bool operator()( size_t i, size_t j ) const
{
return theColl[i] < theColl[j];
}
};
template< typename T >
void makeOrdered( std::vector< T > const& input, std::vector< size_t > & order )
{
order.clear();
size_t len = input.size();
order.reserve( len );
for( size_t i = 0; i < len; ++i )
{
order.push_back( i );
}
PredByIndex<T> pred( input );
std::sort( order.begin(), order.end(), pred );
}
And now "order" will have the ordinal position in the ordered collection.
Of course in C++11 the predicate could be written as a lambda expression rather than having to create the class PredByIndex.
We are not done yet though. We now have an index, not a "find me in the sorted vector". However we can transpose our index as follows:
void transpose_index( std::vector< size_t > const & index,
std::vector< size_t > & trans )
{
// for this to work, index must contain each value from 0 to N-1 exactly once.
size_t size = index.size();
trans.resize( index.size() );
for( size_t i = 0; i < size; ++i )
{
assert( index[i] < size );
// for further assert, you could initialize all values of trans to size
// then as we go along, ensure they still hold that value before
// assigning
trans[ index[i] ] = i;
}
}
Now our transposed index gives you what you want, and the transpose itself is O(N)
In a slightly different example of data, if the inputs are [ 5, 3, 11, 7, 2 ]
The "sorted" order is [ 2, 3, 5, 7, 11 ]
The "index" order is [4, 1, 0, 3, 2] i.e. element 4 is the smallest, then element 1 etc.
The "transpose" order, as we fill it in
[ _, _, _, _, _ ]
[ _, _, _, _, 0 ]
[ _, 1, _, _, 0 ]
[ 2, 1, _, _, 0 ]
[ 2, 1, _, 3, 0 ]
[ 2, 1, 4, 3, 0 ]
This looks like what we want. Our original data 5 is position 2, 3 is position 1, 11 is position 4 etc in the sorted data.

You can use find to search for the element:
int *p1 = std::find(&A[0], &A[5], 5);
int *p2 = std::find(&A_sorted[0], &A_sorted[5], 5);
and use the distance to show the index:
int i1 = p1 - A;
int i2 = p2 - A_sorted;
i1 and i2 now show the index in the corresponding array.

Related

Length of the longest decreasing subsequence built by appending elements to the end and the front using dynamic programming

The restrictions are that the elements can be appended to the front if they are greater than the element at the front and to the back if they are smaller than the back. It can also ignore elements (and there comes the difficulty).
Example:
Input:
{6, 7, 3, 5, 4}
The longest sequence to that input is:
Start with {6}.
Append 7 to the front because it is greater than 6. {7, 6}
Ignore 3.
Append 5 to the back because it is smaller. {7, 6, 5}
Append 4 to the back because it is smaller. {7, 6, 5, 4}
If we appended 3, the sequence would be smaller {7, 6, 3} because then we wouldn't be able to append 4.
I tried to adapt a LIS algorithm to solve it, but the results are totally wrong.
int adapted_LIS(int input[], int n)
{
int score[n] = {};
score[0] = 1;
for (int i = 1; i < n; i++)
{
score[i] = 1;
int front = input[i];
int back = input[i];
for (int j = 0; j < i; j++)
{
if (input[j] > front)
{
front = input[j];
score[i] = std::max(score[i], score[j] + 1);
}
else if (input[j] < back)
{
back = input[j];
score[i] = std::max(score[i], score[j] + 1);
}
}
}
return *std::max_element(score, score + n);
}
How can I solve it using Dynamic Programming?
The optimal substructure that we need for dynamic programming is that, given two sequences with the same front and back, it’s obviously better to extend the longer one (or the same, if the sequences have the same length). Here’s some C++. It’s inefficient for clarity and so that it can’t be fed directly to an online judge, but there’s a straightforward path to O(n³). With a little data structural cleverness, O(n² log n).
#include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <vector>
std::vector<int> PushFront(int x, std::vector<int> subsequence) {
subsequence.insert(subsequence.begin(), x);
return subsequence;
}
std::vector<int> PushBack(std::vector<int> subsequence, int x) {
subsequence.push_back(x);
return subsequence;
}
void Consider(std::map<std::pair<int, int>, std::vector<int>> &table,
std::vector<int> subsequence) {
std::vector<int> &entry = table[{subsequence.front(), subsequence.back()}];
if (subsequence.size() > entry.size()) {
entry = std::move(subsequence);
}
}
std::vector<int> TwoSidedDecreasingSubsequence(const std::vector<int> &input) {
if (input.empty()) {
return {};
}
// Maps {front, back} to the longest known subsequence.
std::map<std::pair<int, int>, std::vector<int>> table;
for (int x : input) {
auto table_copy = table;
for (const auto &[front_back, subsequence] : table_copy) {
auto [front, back] = front_back;
if (x > front) {
Consider(table, PushFront(x, subsequence));
}
if (back > x) {
Consider(table, PushBack(subsequence, x));
}
}
Consider(table, {x});
}
return std::max_element(
table.begin(), table.end(),
[&](const std::pair<std::pair<int, int>, std::vector<int>> &a,
const std::pair<std::pair<int, int>, std::vector<int>> &b) {
return a.second.size() < b.second.size();
})
->second;
}
int main() {
for (int x : TwoSidedDecreasingSubsequence({6, 7, 3, 5, 4})) {
std::cout << ' ' << x;
}
std::cout << '\n';
}

Count the number of occurrences of one vector entirely in another vector

I am writing a simple function that returns an integer indicating the number of times the
contents of one vector appear in another.
For Example:
vector<int> v1 {1, 4, 2, 4, 2, 1, 4, 2, 9, 1, 4, 2, 0, 1, 4, 2};
vector<int> v2 {1, 4, 2};
cout << countOccurrences(v1, v2);
Should return 4.
Here is my iterative solution
int countOccurrences(vector<int> &v1, vector<int> &v2) {
int i, j, count = 0;
for(i = 0; i <= v1.size() - v2.size(); ++i) {
for(j = 0; j < v2.size(); ++j) {
if(v1[i + j] != v2[j])
break;
}
if(j == v2.size())
++count;
}
return count;
}
I want to write the same function recursively but I am clueless. I am new to recursion and It seems intimidating to me.
Here's one way (in pseudo code):
int countOccurrences(vector<int> &v1, vector<int> &v2) {
if v1 is shorter than v2
return 0;
if v1 starts with v2
return 1 + countOccurrences( v1[1:], v2 )
else
return countOccurrences( v1[1:], v2 );
}
Recursion is a bit easier if you use iterators:
template <typename IT>
int count_occurences(IT begin,IT end,IT s_begin,IT s_end) {
auto it = std::search(begin,end,s_begin,s_end);
auto dist = std::distance(s_begin,s_end);
if (it == end) return 0;
return 1 + count_occurences(it+dist,end,s_begin,s_end);
}
std::search searches for one range, [s_begin,s_end), inside another range, [begin,end). I suppose you do not want to use it, so I leave it to you to replace it with your handwritten way to find one inside the other. The recursion comes into play by accumulating 1 when the sequence was found and call the function again only for the remainder of the vector.
Complete Example
yet, a c++ 20 solution :
#include <vector>
#include <span>
#include <algorithm>
int countOccurrences(std::span<int> data, std::span<int> needle)
{
if (data.size() < needle.size())
return 0;
if (std::equal(needle.begin(), needle.end(), data.begin()))
return 1 + countOccurrences(data.subspan(1), needle);
else
return countOccurrences(data.subspan(1), needle);
}
int main()
{
std::vector<int> data{ 1, 4, 2, 4, 2, 1, 4, 2, 9, 1, 4, 2, 0, 1, 4, 2 };
std::vector<int> needle{ 1, 4, 2 };
printf_s("%d\n", countOccurrences(data, needle));
}
this is much faster than using sub vectors each recursion because it is only a view ! no allocation !
This code is based on the pseudo-code provided by Scott Hunter.
bool start_with(vector<int> &v1, vector<int> &v2) {
for(auto i = 0; i < v2.size(); ++i)
if (v1[i] != v2[i])
return false;
return true;
}
int countOccurrences(vector<int> &v1, vector<int> &v2) {
static int i = 0;
if(v1.size() < v2.size()) {
return 0;
}
else if(start_with(v1, v2)) {
vector<int> temp(v1.begin() + i + 1, v1.end());
return 1 + countOccurrences(temp, v2);
}
vector<int> temp(v1.begin() + i + 1, v1.end());
return countOccurrences(temp, v2);
}
Feel free to suggest an alternative to the lazy hack i.e. static variable that does not change the function prototype.

Initialize matrix with all the combinations from an array of objects in C++

I'm a newbie programmer trying to solve the following problem: I need to initialize a matrix with all the combinations from a array of objects so I can extract the values and perform certain calculations afterwards for each set of objects, in this case I used a struct for X, Y coordinates to represent the data. The entire data set consists on 35 coordinates, for now I'm dealing with as few data as possible, an input array of size 4, meaning 4 (n) combinations of 3 (r) objects. The program seems to work fine until I print the 4x3 matrix and find out I was only able to store the first combination, and after tinkering with the program I got stuck since I didn't code this program entirely. Could someone suggest me a solution so the matrix gets initialized correctly? I'd highly appreciate it.
#include <iostream>
#define n 4 //data set size
#define r 3 // combination size
using namespace std;
struct Points{
double x, y;
};
void Combination(Points Data [n], Points CombinationMatrix [][r],int start, int currLen, bool check []) {
// Return if the currLen is more than the required length.
if(currLen > r)
return;
// If currLen is equal to required length then add the sequence.
else if (currLen == r){
for (int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
if (check[i] == true){
CombinationMatrix[i][j] = Data[j];
}
}
}
return;
}
// If start equals to len then return since no further element left.
if (start == n)
{
return;
}
// For every index we have two options.
// First is, we select it, means put true in check[] and increment currLen and start.
check[start] = true;
Combination(Data, CombinationMatrix, start + 1, currLen + 1, check);
// Second is, we don't select it, means put false in check[] and only start incremented.
check[start] = false;
Combination(Data, CombinationMatrix, start + 1, currLen, check);
}
int main()
{
Points Data [n] = { {1, 1} , {2, 7} , {3, 6} , {4, 13}}; //, {5,9} ,
//{6, 7} , {7, 12} , {8, 14} , {9, 17} , {10, 23} ,
//{11,28} , {12, 63} , {13, 45} , {14, 68} , {15, 32} ,
//{16,98} , {17, 115} , {18, 116}, {19, 112}, {20, 115},
//{21, 88} , {22, 86} , {23, 106}, {24, 136}, {25, 158},
//{26, 198}, {27, 128} , {28, 187}, {29, 112}, {30, 149},
//{31, 279}, {32, 224} , {33, 222}, {34, 260}, {35, 166}};
Points CombinationMatrix [n][r];
bool check[n];
for(int i = 0; i < n; i++){
check[i] = false;
}
Combination(Data, CombinationMatrix, 0, 0, check);
for (int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
cout << CombinationMatrix[i][j].x << "," << CombinationMatrix[i][j].y << " ";
}
cout << endl;
}
return 0;
}
I suggest that you have a look at std::prev_permutation.
If you have a std::vector<Data> points, then you can get all permutations via
do {
// Do something with the current permutation
for ( int i = 0; i < points.size(); ++i ) {
std::cout << points[i] << ' ';
}
std::cout << '\n';
} while ( std::prev_permutation(points.begin(),points.end()) );
Since this gives you points.size()! (Factorial) combinations, I would not store it in a matrix unless you have a very good reason to do so.
std::prev_permutation uses the lexicographically smaller. Thus, you need to overload the operator < for Data.
inline bool operator< (const Data& lhs, const Data& rhs){
/* do actual comparison e.g.*/
return ((lhs.x <rhs.x) && (lhs.y <rhs.y));
}
The following generates combinations of your array using std::prev_permutation.
Note that this is accomplished by using a bool vector that starts with r of those bits set to true, and on each iteration the bits in the bool vector have their positions changed.
The following uses std::vector<Point> instead of hard-coded arrays. This adds flexibility in that you don't have to guess how many combinations will be generated.
#include <iostream>
#include <vector>
#include <algorithm>
struct Points {
double x, y;
};
std::vector<std::vector<Points>> Combination(std::vector<Points>& Data, int n, int r)
{
// The returned vector
std::vector<std::vector<Points>> retVect;
// Array of bools
std::vector<bool> bits(n);
// Fill the first r positions of the bool array to true
std::fill(bits.begin(), bits.begin() + r, true);
// Our temporary 1 dimensional array we use when building a single combination
std::vector<Points> tempV;
do
{
tempV.clear();
for (int i = 0; i < n; ++i)
{
// for each item in the bool array that's true, add that to the vector
if (bits[i])
tempV.push_back(Data[i]);
}
// add this combination to vector of combinations
retVect.push_back(tempV);
// rearrange the bits
} while (std::prev_permutation(bits.begin(), bits.end()));
return retVect;
}
int main()
{
std::vector<Points> Data = { {1, 1}, {2, 7}, {3, 6}, {4, 13} };
auto CombinationMatrix = Combination(Data, 4, 3);
for (size_t i = 0; i < CombinationMatrix.size(); i++) {
for (size_t j = 0; j < CombinationMatrix[i].size(); j++) {
std::cout << "{" << CombinationMatrix[i][j].x << "," << CombinationMatrix[i][j].y << "} "; }
std::cout << std::endl;
}
}
Output:
{1,1} {2,7} {3,6}
{1,1} {2,7} {4,13}
{1,1} {3,6} {4,13}
{2,7} {3,6} {4,13}

How to remove every second value from a C++ array without making a copy of the array?

Problem: I want to get an array A[6] = {6, 5, 4, 3, 2, 1} to be A[6] = {5, 3, 1, 1, 1, 1}. In other words - "delete" every second value starting with 0th and shift all other values to the left.
My Attempt:
To do that I would use this code, where a - length of the relevant part of an array A (the part with elements that are not deleted), ind - index of the value that I want to delete.
for (int j = ind; j < n; j++)
A[j] = A[j+1];
However, I couldn't get this to work, using the code like that:
void deleting(int A[], int& a, int ind){
for (int j = ind; j < a; j++)
A[j] = A[j+1];
a--;
}
int A[6] = {6, 5, 4, 3, 2, 1};
a = 6
for (int i = 0; i < a; i+=2)
deleting(A, a, i);
After running this code I was getting A[6] = {5, 4, 2, 1, 1507485184, 1507485184}. So, it deleted the elements at indexes 0, 3. Why did it delete the 3rd index?
There are two ways to do this:
walk the array, copying the last n-i elements forward one place for every even i, or
figure out the eventual state and just go straight to that. The eventual state is the first n/2 places are array[i]=array[2*i + 1], and the last n/2 places are just copies of the last element.
The first method is what you asked for, but it does multiple redundant copy operations, which the second avoids.
As for your implementation problems, examine what happens when j=n-1, and remember A[n] is not a valid element of the array.
I suggest making the copy-everything-forward operation its own function anyway (or you can just use memcpy)
For these kinds of problems (in-place array manipulation), it's a good idea to just keep an index or pointer into the array for where you are "reading" and another where you are "writing." For example:
void odds(int* a, size_t len) {
int* writep = a;
int* readp = a + 1;
while (readp < a + len) { // copy odd elements forward
*writep++ = *readp;
readp += 2;
}
while (writep < a + len - 1) { // replace rest with last
*writep++ = a[len - 1];
}
}
Just for kicks, here is a version which doesn't use a loop:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <utility>
#include <initializer_list>
template <typename T, std::size_t Size>
std::ostream& print(std::ostream& out, T const (&array)[Size]) {
out << "[";
std::copy(std::begin(array), std::end(array) -1,
std::ostream_iterator<T>(out, ", "));
return out << std::end(array)[-1] << "]";
}
template <std::size_t TI, std::size_t FI, typename T, std::size_t Size>
bool assign(T (&array)[Size]) {
array[TI] = array[FI];
return true;
}
template <typename T, std::size_t Size,
std::size_t... T0>
void remove_even_aux(T (&array)[Size],
std::index_sequence<T0...>) {
bool aux0[] = { assign<T0, 2 * T0 + 1>(array)... };
bool aux1[] = { assign<Size / 2 + T0, Size - 1>(array)... };
}
template <typename T, std::size_t Size>
void remove_even(T (&array)[Size]) {
remove_even_aux(array, std::make_index_sequence<Size / 2>());
}
int main() {
int array[] = { 6, 5, 4, 3, 2, 1 };
print(std::cout, array) << "\n";
remove_even(array);
print(std::cout, array) << "\n";
}
If C++ algorithms are an option, I tend to prefer them by default:
auto *const end_A = A + (sizeof(A)/sizeof(*A));
auto *new_end = std::remove_if(
A, end_A,
[&A](int const& i) { return (&i - A) % 2 == 0; });
// Now "erase" the remaining elements.
std::fill(new_end, end_A, 0);
The std::remove_if algorithm simply moves the elements that do not match the predicate (in our case, test if the address is MOD(2)=0), and std::moves them to the end. This is in place. The new "end" is return, which I then indexed over and set the elements to 0.
So if it has to be an array the solution would be like this:
void deleting(int A[size], int size){
for (int i = 0; i < size / 2; i++)
A[i] = A[2 * i + 1];
for (int i = size / 2; i < size; i++)
A[i] = A[size / 2];
}
You first loop through first half of the array "moving" every second number to the front, and then you loop through the rest filling it with the last number.
For a more versatile version of other's answers:
#include <iostream>
template<typename InputIt, typename T>
void filter(InputIt begin, InputIt end, T const& defaultvalue)
{
InputIt fastforward = begin;
InputIt slowforward = begin;
fastforward++; // starts at [1], not [0]
while (fastforward < end)
{
*slowforward = *fastforward;
++slowforward;
++ ++fastforward;
}
while (slowforward < end) // fill with default value
{
*slowforward++ = defaultvalue;
}
}
int main()
{
int A[6] = {6, 5, 4, 3, 2, 1};
std::cout << "before: ";
for (auto n : A)
std::cout << n << ", ";
std::cout << std::endl;
filter(A, A+6, 1);
std::cout << "after: ";
for (auto n : A)
std::cout << n << ", ";
std::cout << std::endl;
}
Outputs:
before: 6, 5, 4, 3, 2, 1,
after: 5, 3, 1, 1, 1, 1,
And this works with std::array<bool>, std::vector<std::string>, std::unordered_set<void*>::iterator, etc.
The common way of doing this would be keeping two indices: one to the entry you're modifying and the other to the entry you intend to process
const auto size = sizeof(A) / sizeof(int);
// N.b. if size == 1 entire array is garbage
int i = 0;
for (int nv = 1; nv < size; ++i, nv += 2)
A[i] = A[nv];
--i;
// Significative array is now [0;N/2[, fill with last now
for (int j = i + 1; j < size; ++j)
A[j] = A[i];
This grants an in-place-modify fashion.
you can combine std::remove_if and std::fill to do this
example code:
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int A[6] = {6, 5, 4, 3, 2, 1};
auto endX = std::remove_if(std::begin(A),std::end(A),[&A](const int& i){return (&i-A)%2==0;});
if(endX!=std::begin(A))//in case nothing remained, although not possible in this case
std::fill(endX,std::end(A),*(endX-1));
//else /*something to do if nothing remained*/
for(auto a : A)std::cout<<a<<' ';
}

Array Split in C++

I am trying to split an array, and this is how I am doing it:
int arr1[] = {1, 2, 3, 4, 5};
int *arr2 = arr1 + 1;
Now I need to do this in a loop. In every iteration, I am trying to decrease the size of the array by 1 element or 2 elements based on a condition. For obvious reasons I can't declare int arr2[some_variable] .
But I want a new array to be created in every iteration of the loop whose size is 1 less than its parent array. I am not sure how I can achieve this. Can anyone help please?
In Java, there is a function which can do this: int newArr[] = Arrays.copyOfRange(arr, 1, arr.length); I wanted something similar to this in C++.
Use std::vector<int> from the C++ standard library:
#include <string>
#include <iostream>
#include <vector>
void dump(std::vector<int> &v)
{
for (std::vector<int>::iterator it = v.begin(); it != v.end(); it++)
std::cout << *it << " ";
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(a, a + 5);
std::vector<int> v2(v.begin() + 1, v.begin() + 4);
dump(v);
std::cout << std::endl;
dump(v2);
}
And if you really-really-really can't use vector (why, seriously?), then just memcpy.
int arr[] = { 1, 2, 3, 4, 5 };
int cp[3];
memcpy(cp, arr + 1, sizeof(cp));
I'm not sure exactly why you want to have a new one each time, but you can use a standard container, like std::vector:
std::vector<int> arr1{1, 2, 3, 4, 5}; //std::iota is another option
int index{};
/*loop header*/ {
//make sure arr1.size() is at least 1
std::vector<int> arr2(std::next(std::begin(arr1), ++index), std::end(arr1));
}
I use std::next because it works in more scenarios. All this does is create a vector from two iterators: as far past the beginning as necessary, and the end (one past because it's exclusive).
Though C++11 is nice, it's not always a reality. In that case, this should work:
int arr1temp[] = {1, 2, 3, 4, 5};
std::vector<int> arr1(arr1temp, arr1temp + sizeof(arr1temp)/sizeof(arr1temp[0]));
int index = 0;
/*loop header*/ {
//make sure arr1.size() is at least 1
std::vector<int>::iterator start = arr1.begin();
std::advance(start, ++index);
std::vector<int> arr2(start, arr1.end());
}
/why/ do you think you need to make a copy of the array? Pointers and arrays are somewhat interchangeable, so all you need to do is track size and modify that.
void doSomethingWithArray(int* array, size_t arraySize) {
....
}
const size_t arraySize = 5;
int arry1[arraySize] = { 1, 2, 3, 4, 5 };
int* array = arr1;
int* arrayEnd = arr1 + arraySize;
for (int i = 0; i < 10; ++i) {
if ((*array) & 1 == 1) {
array += 1;
} else {
array += 3;
}
if(array >= arrayEnd)
break;
size_t howBigIsMySlice = arrayEnd - array;
if(howBigIsMySlice > && (rand() % 1) == 0)
howBigIsMySlice -= 1;
doSomethingWithArray(array, howBigIsMySlice);
}
You made no copies of data, and as far as "doSomethingWithMyArray" is concerned, the array is as big as we tell it.