Insert value at the beginning and the end of 2d vector
Feb 7, 2019 at 8:07am UTC
Hi everyone. I am new to c++ programming. Given a task to insert zero at the beginning and the end of each row of 2d vector. I had try to code it but errors occurred. I don't know how to solve it. Hope someone can help me. Thanks.
Here is the input file:
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
5 4 3 2 1 9 8 7 6
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
#include <iostream>
#include <vector>
#include <iomanip> // setw
#include <fstream>
using namespace std;
const int m = 3;
const int n = 9;
vector<vector<int > > route(m, vector <int >(n, 0));
int main()
{
// Input file
ifstream inpData("mydata.txt" );
// Assign route into array
cout << "The vector elements before insert '0' are: " ;
cout << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
inpData >> route[i][j];
cout << setw(3) << route[i][j] << ' ' ;
}
cout << endl;
}
cout << endl;
// Close input files
inpData.close();
for (int row = 0; row < m; row++)
{
// inserts 0 at begin of vector
vector<int >::iterator it = route.insert(route.begin(), 0);
// insert 0 at the end of vector
vector<int >::iterator it = route.insert(route.end(), 0);
}
cout << "The vector elements after insert '0' are: " ;
cout << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < route[i].size(); j++)
{
cout << setw(3) << route[i][j] << ' ' ;
}
cout << endl;
}
cout << endl;
return 0;
}
The output should be:
0 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 0
0 5 4 3 2 1 9 8 7 6 0
Feb 7, 2019 at 8:13am UTC
The vector that you want to insert into is route[row].
route[row].insert(route[row].begin(), 0);
Feb 7, 2019 at 8:34am UTC
Thanks Peter87 . Its work after I insert route[row]
and remove vector<int >::iterator it =
for line 42.
Thank you for your help.
Topic archived. No new replies allowed.