473,487 Members | 2,622 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

2D Array

How can I implement a 2D array using vector or container classes in
C++.....

Oct 23 '06 #1
4 1799
krish wrote:
How can I implement a 2D array using vector or container classes in
C++.....
std::vector< std::vector< T my2Darray;

Oct 23 '06 #2

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
Oct 23 '06 #3

BobR wrote:
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

thanks a lot for the answers..
One thing is what coming to my mind is that cant the rows and coloumn
can be decided at the run-time. I mean to say if I am not sure of the
size of the rows and coloumns...and want it to increase or decrease at
the run-time.

Oct 24 '06 #4

krish wrote in message
<11**********************@i3g2000cwc.googlegroups. com>...
>
thanks a lot for the answers..
One thing is what coming to my mind is that cant the rows and coloumn
can be decided at the run-time. I mean to say if I am not sure of the
size of the rows and coloumns...and want it to increase or decrease at
the run-time.
No problem. You can just '*.push_back()' more elements, or use '*.resize()'
as needed.

Check this out:

// includes here <iostream>, <ostream>, <vector>, etc.

void PrintVec( std::vector<intconst &vec, std::ostream &sout){
sout<<" size="<<vec.size()<<" cap="<<vec.capacity()<<std::endl;
return;
} // PrintVec( vector<intconst &, ostream&)

int main(){
using std::cout;
cout<<"\n--- VecInt(10) size test ---"<<std::endl;
std::vector<intVecInt(10);
PrintVec( VecInt, cout);
VecInt.push_back( 1 );
PrintVec( VecInt, cout);
for(size_t i(0); i < 11; ++i){ VecInt.push_back( i );}
PrintVec( VecInt, cout);
VecInt.resize( 50 );
PrintVec( VecInt, cout);
VecInt.push_back( 1 );
PrintVec( VecInt, cout);
VecInt.resize( 40 );
PrintVec( VecInt, cout);
cout<<"--- VecInt(10) size test ---END"<<std::endl;
return 0;
} // main end

/* --- output ---
--- VecInt(10) size test ---
size=10 cap=10
size=11 cap=20
size=22 cap=40
size=50 cap=50
size=51 cap=100
size=40 cap=100
--- VecInt(10) size test ---END
*/

Note how '.resize(50)' set the capacity to 50 (instead of doubling the
capacity).
Then note that '.resize(40)' reduced the size, but not the capacity.

--
Bob R
POVrookie
Oct 24 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2754
by: Brian | last post by:
I'm diddlying with a script, and found some behavior I don't understand. Take this snippet: for ($i = 0; $i <= count($m); $i++) { array_shift($m); reset($m); }
2
575
by: Stormkid | last post by:
Hi Group I'm trying to figure out a way that I can take two (two dimensional) arrays and avShed and shed, and subtract the matching elements in shed from avShed I've pasted the arrays blow from a...
15
5153
by: lawrence | last post by:
I wanted to test xml_parse_into_struct() so I took the example off of www.php.net and put this code up on a site: <?php $simple = <<<END <item>
8
3460
by: vcardillo | last post by:
Hello all, Okay, I am having some troubles. What I am doing here is dealing with an employee hierarchy that is stored in an array. It looks like this: $employees = array( "user_id" => array(...
12
55523
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are...
8
10195
by: Mike S. Nowostawsky | last post by:
I tried using the "toUpperCase()" property to change the value of an array entity to uppercase BUT it tells me that the property is invalid. It seems that an array is not considered an object when...
58
10041
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
104
16845
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
7
3165
by: Jim Carlock | last post by:
Looking for suggestions on how to handle bad words that might get passed in through $_GET variables. My first thoughts included using str_replace() to strip out such content, but then one ends...
17
7210
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need...
0
7106
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6967
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6846
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7349
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4874
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3076
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1381
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
600
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
267
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.