I am a beginner in c++. how to iterate in double dimensional vector in c++ stl?
int main()
{
vector< vector<int>> vec;
for(int i=0;i<vec.size();i++
cout<<vec[i]<<" "<<endl;
}
I am a beginner in c++. how to iterate in double dimensional vector in c++ stl?
int main()
{
vector< vector<int>> vec;
for(int i=0;i<vec.size();i++
cout<<vec[i]<<" "<<endl;
}
While the solution with indices is certainly right, the following variant with ranged for
loops is more modern. It is a bit less flexible but for just using the values it works perfectly and has less chances for errors.
int main(){
std::vector<std::vector<int>> vec;
// add some data to vec
for(const auto &v: vec){ // the & is important otherwise you copy the inner vector
for(const auto &i: v){
std::cout << i << ' ';
}
std::cout << '\n';
}
return 0;
}
If you want to modify the elements, you have to get rid of the const
s.
You can iterate like this,
int main()
{
vector< vector<int>> vec;
for(int i=0;i<vec.size();i++)
{
for(int j=0;j<vec[i].size();j++)
cout<<vec[i][j]<<" ";
cout<<endl;
}
}
You can use Range-based for loop like this
std::vector<std::vector<int>> vecOFvec{{1,2},{3,4,5},{6,7,8,9}};
for(const auto& elemOuter:vecOFvec){
std::cout<<"\n";
for(const auto& elemInner:elemOuter)
std::cout<<elemInner<<" ";
}
Output
1 2
3 4 5
6 7 8 9
Lets you have a 2D Mattrix in Array
int matt[R][C];
Iterating the 2D Array
for(int r=0; r < R; r++){
for(int c=0; c<C;c++)
cout << matt[r][c];
cout << endl;
}
Similarly for 2D vector, you first need the number of rows
We get that by vec.size();
Then we need the column size
we get that by vec[0].size() or vec[i].size()
This simply means the size of the column corresponding to the 0th or ith row
for(int i=0; i< vec.size(); i++){
for(int j=0; j<vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
You can use an iterator to iterate through the vector but remember Iterator stores snapshot the vector/array and the beginning of the iteration. If the vector changes its size during for loop you might face some problems