ralph wrote in message
<11**********************@b28g2000cwb.googlegroups .com>...
>krish wrote:
>How can I implement a 2D array using vector or container classes in
C++.....
std::vector< std::vector< T my2Darray;
If a newbie doesn't know about 'std::vector', (s)he probably does not know
how to use it either (esp. 2D, 3D). So, I'll present a little snippet:
[ sure hope this ain't homework!! ]
// ------------
// --- std includes ---
#include <iostream>
#include <ostream>
#include <vector>
#include <stdexcept>
// #include <exception// usually in <stdexcept>
// ------------
int main(){
using std::cout; // for NG posting
using std::size_t; // for NG posting
size_t rows(6);
size_t cols(4);
// -- wrong: std::vector<std::vector<int>vec2D( rows, cols );
// -- there is a 'space' missing between '>>'. Error!
// std::vector<std::vector<int vec2D( rows, cols );
std::vector<std::vector<int vec2D( rows,
// std::vector<int>( cols, int(7) ) ); // alt.
std::vector<int>( cols, 7 ) ); // init all elements to int(7).
if( 4 < rows ){
vec2D.at( 4 ).push_back( 22 ); // you can add to vector
vec2D.at( 2 ).at( 0 ) = 15; // and modify
}
try{
for(size_t i(0); i < vec2D.size(); ++i){
for(size_t j(0); j < vec2D.at(i).size(); ++j){
cout<<" vec2D.at("<<i<<").at("<<j<<")= "
<<vec2D.at(i).at(j)<<std::endl;
// because you are positive about index being
// in range here, you could use: (remove the try-catch):
// cout<<" vec2D[ i ][ j ]= " << vec2D[ i ][ j ]
// <<std::endl;
} // for(j)
} // for(i)
// this next line will 'throw out_of_range()' ( from 'at()' )
cout<<" vec2D.at(6).at(4)= "
<<vec2D.at(6).at(4)<<std::endl;
// if you want program to 'crash', try:
// cout<<" vec2D[6][4]= " << vec2D[6][4] <<std::endl;
} // try
catch(std::out_of_range &Oor){
cout<<"caught "<<Oor.what()<<std::endl;
}
return 0;
} // main()
// ---------------
( You could use 'iterators' in the for() loops, instead of the 'size_t' I
showed. )
[ ...but then, IMHO, it looks ugly/cluttered. <Ghint: typedef. ]
Read-up on 'std::vector' for MUCH more.
--
Bob R
POVrookie