Hi everyone. I would like to ask. I got a task to split or divide vector and copy it into new vector. I don't have idea how to do it. Is there any ways to do it? Any advice greatly appreciated.
The situation is as follows:
In the following code, vector has been summed up and each time the amount of the summation reaches 15, zero will be inserted. But now, in the next task I need to split the vector each time the summation reaches 15. The new vector need to be creates from each vector row.
Original vector:
0 5 3 2 4 6 7 1 6 5 3 1 8 6 1 9 3 2 1
0 0 6 7 1 6 5 3 9 3 2 1 7 6 2 5 3 2 4
0 8 6 1 9 3 3 1 6 7 1 5 2 3 4 6 5 3 1
Here is the output I got after inserting zero:
0 5 3 2 4 0 6 7 1 0 6 5 3 1 0 8 6 1 0 9 3 2 1
0 0 6 7 1 0 6 5 3 0 9 3 2 1 0 7 6 2 0 5 3 2 4
0 8 6 1 0 9 3 3 0 1 6 7 1 0 5 2 3 4 0 6 5 3 1
Now, after split, the output should be as:
New vector for row 1:
0 5 3 2 4
0 6 7 1
0 6 5 3 1
0 8 6 1
0 9 3 2 1
New vector for row 2:
0 0 6 7 1
0 6 5 3
0 9 3 2 1
0 7 6 2
0 5 3 2 4
New vector for row 3:
0 8 6 1
0 9 3 3
0 1 6 7 1
0 5 2 3 4
0 6 5 3 1
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
const int row = 3;
const int col = 19;
vector<vector<int> > vec(row, vector <int>(col, 0));
vector<vector<int> > new_vec_row1(5, vector <int>(5, 0));
vector<vector<int> > new_vec_row2(5, vector <int>(5, 0));
vector<vector<int> > new_vec_row3(5, vector <int>(5, 0));
int main ()
{
// Input file
ifstream inpData("myData.txt");
// Assign data into array
cout << "Original vector: ";
cout << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
inpData >> vec[i][j];
cout << " " << vec[i][j];
}
cout << endl;
}
cout << endl;
// Close input files
inpData.close();
for (int i = 0; i < row; i++)
{
int sum = 0;
int Q = 15;
// Iterator used to store the position of searched element
vector<int>::iterator itr;
for (itr = vec[i].begin(); itr != vec[i].end(); itr++)
{
if (sum + *itr > Q)
{
// inserting an element invalidates the iterator, get a new one
itr = vec[i].insert(itr, 0);
sum = 0;
}
sum += *itr;
}
}
// Print new vector
cout << "New vector with inserting element: ";
cout << endl;
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
cout << " " << vec[i][j];
}
cout << endl;
}
cout << endl;
system("pause");
return 0;
}
|