Hi,
I am beginner in C++ and need your help.
Suppose I have a std::vector (let's call it myVec) of size N which is containing numbers. myVec has to be split up into unknown number of sub-vectors.
My difficulty is that I don’t know the number of needed sub-vectors at forehand (also don't know the length of each vector).
Simple example: myVec has to be split up when the difference of between two number is larger than a given number (let’s call it X)
myVec={100,103,109,110,130,138,140,144}
1)X=10 ==> newVec1={100,103,109,110} , newVec2={130,138,140,144}
2)X=5 ==> newVec1={100,103} , newVec2={109,110}, newVec3={130}, NewVec4={138,140,144}
In first example I need to create just two newVec, but in second example 4 newVec must be created.
As I know the name of each vector must be unique. So, How do I create vectors when I don’t know how many needed?
create a vector ("ResultVectors") to hold you new result vectors.
when you find you need one, instantiate a vector in the normal way then push_back onto your ResultVectors. In this way you dont need to know how many vectors need to be created you just create one and push_back().
But I need to save each group of new result in different vector and keep them until end of my program. I have to do different calculations and comparison on each newVec.
When I have just one “ResultVectors”, it is difficult to manage different groups of data.
#include<vector>
// Example program
int main()
{
std::vector<std::vector<int>> ResultsVector;
// when you need a vector create one e.g.
std::vector<int> newVec1 = { 100, 103, 109, 110 };
// and another one
std::vector<int> newVec2 = { 109, 110 };
// etc etc, create as many as you want, then add them
// to your results vector. It doesn't matter how many vectors
//OR how many elements each vector has
ResultsVector.push_back(newVec1);
ResultsVector.push_back(newVec2);
return 0;
}
edit:
and iterate over your results something like this:
1 2 3 4 5 6 7 8 9 10
for (int i = 0; i < ResultsVector.size(); i++)
{
std::vector<int> v = ResultsVector.at(i);
for (int j = 0; j < v.size(); j++)
{
std::cout << v.at(j) << ",";
}
std::cout << std::endl;
}
Not all of your variables have to have an explicit name. Whenever you have to keep an unknown number of values is when you need a "collection" kind of variable like an array or vector.
The nice thing about such variables is you can store other collections in your collection. In other words, you can have an array of arrays, or a vector of vector, etc.
Look back at the answers offered to you to see what you can do to store your values.