Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to make several subvectors with lengths following elements of another vector
For example :
vector<int> A{2,3}
// Vector A has 2 elements, therefore I need to make 2 subvectors

A[0] = 2, make a new subvector with length of 2, example : B {11,12}	
A[1] = 3, make a new subvector with length of 3, example : C {13,14,15}

With vector of vector, I need to fill the inner vector first (subvectors) and pass it to the outer vector. However, in my case I need to fill the outer vector first, and make subvectors based on that : how many elements it has (to be used as number of subvectors) and the value of each elements (to be used as the size of each subvectors).

What I have tried:

I tried to initialize subvectors inside of a loop, however I don't know how to increment it.
int data = 0;
vector<int> A{2,3}; --> // An example, in the actual implementation this vector size is unkwown and elements are filled using cin.

for (int i = 0; i < A.size(); i++){
	vector<int> B(A[i]); 
    //a subvector with size of A[i]
    //is it possible to increment this object ?
				
	for (int j = 0; j < A[i]; j++){
		cin >> data;
		B.push_back(data); //need to push the next i iteration to a new subvector
	}	
}
Posted
Updated 21-Feb-22 23:58pm
v4

1 solution

You need a containers for your subvectors. You might, for instance, use a vector of vectors:
#include <iostream>
#include <vector>
using namespace std;

int main()
{

  vector<int> v{2,3};
  vector < vector < int > > sv; // the sub-vectors

  for (size_t i = 0; i < v.size(); ++i)
  {
    sv.push_back(vector<int>{});
    for (int j = 0; j < v[i]; ++j)
    {
      sv[i].push_back(rand()); // just for testing, random initialization
    }
  }


  for (size_t i = 0; i < v.size(); ++i)
  {
    for (size_t j = 0; j < sv[i].size(); ++j)
      cout << sv[i][j] << " ";
    cout << endl;
  }

}
 
Share this answer
 
Comments
lock&_lock 22-Feb-22 6:27am    
Exactly what I need ! I wasn't aware of this approach before, I have learned something new from your answer, thank you very much !
CPallini 22-Feb-22 6:53am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900