I\'m using the vector class in the STL library for the first time. How should I add to a specific row of the vector array?
struct x{
vector
//initialize the 2D vector first
vector<vector<int>> matrix;
//initialize the 1D vector you would like to insert into matrix
vector<int> row;
//initializing row with values
row.push_back(val1);
row.push_back(val2);
//now inserting values into matrix
matrix.push_back(row);
//output- [[val1,val2]]
I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:
// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);
Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?
vector<vector> matrix(row, vector(col, 0));
This will initialize a 2D vector of rows=row and columns = col with all initial values as 0. No need to initialize and use resize.
Since the vector is initialized with size, you can use "[]" operator as in array to modify the vector.
matrix[x][y] = 2;
We can easily use vector as 2d array. We use resize() method for this purpose. The code below can be helpful to understand this issue.
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int row, col;
cin>>row>>col;
vector <vector<int>> v;
v.resize(col,vector<int>(row));
//v = {{1,2,3}, {4,5,6}, {7,8,9}};
/** input from use **/
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
cin>>v[i][j];
}
}
for(int i=0;i<row; i++)
{
for(int j=0;j<col;j++)
{
cout<<v[i][j]<<" ";
}
}
return 0;
}
If you know the (maximum) number of rows and columns beforehand, you can use resize() to initialize a vector of vectors and then modify (and access) elements with operator[]. Example:
int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;
std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));
// Read from matrix.
int value = matrix[1][2];
// Save to matrix.
matrix[3][1] = 5;
Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column]
.
I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <vector <int> > matrix;
size_t row=3 , col=3 ;
for(int i=0,cnt=1 ; i<row ; i++)
{
for(int j=0 ; j<col ; j++)
{
vector <int> colVector ;
matrix.push_back(colVector) ;
matrix.at(i).push_back(cnt++) ;
}
}
matrix.at(1).at(1) = 0; //matrix.at(columns).at(rows) = intValue
//printing all elements
for(int i=0,cnt=1 ; i<row ; i++)
{
for(int j=0 ; j<col ; j++)
{
cout<<matrix[i][j] <<" " ;
}
cout<<endl ;
}
}