TW93 - 13 days ago 4
C++ Question

# How to return the index where values change in a c++ vector?

Sorry for the vague title, I'm not sure how to word it.

Say I have a vector:

``````vector<int> vec{{
1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 14
}};
``````

and a corresponding positions vector which occurs after a number is missed (like 5 to 7).

``````vector<int> positions{{
1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1
}};
``````

How would I return a 2D vector running from each 1, up to but not including the next one: e.g.

``````1 2 3 4 5
7 8 9 10
12 13 14
``````

Thanks in advance, I'd post my attempts, but they all led down blind avenues. I know it's an odd structure...

There are a few ways to solve this, but I believe this should work:

``````std::vector<std::vector<int>> vec2D;
int index = -1;
// Identify the indices of the position vector and use that to identify the
// correct indices of the vec.
for (int i = 0; i != position.size(); ++i)
{
// if the value at i of the position vector is 0,
// push_back the value at i of the vec vector into
// the correct vector of vector.
if (0 == position[i])
{
vec2D[index].push_back(vec[i])
}
else if (1 == position[i])
{
++index; //increment to the next vector
std::vector<int> temp;
vec2D.push_back(temp);
vec2D[index].push_back(vec[i])
}
}
``````