how can i get a character input in a 2d array?
how can i get a character input in a 2d array?
Depending on whether you need to input all the elements, you need to run a loop.Code:char d2array[50][50]; cin>>d2array[x][y]; //where x,y < 50
##I came across a handy *hack* when first learning dynamic allocation months ago, which according to most books..is impossible, but I tested in two compilers and it worked seamlessly.
where a and b are variables ...and the array apparently gets dynamically allocated..Why does this work?..is this compiler specific ? ##Code:char d2array[a][b];
i need to insert a line in that array!!!
just like in sngle dimensional arrays we use getline function!!!
and you expressed that as character input?
I'm still not sure what you are trying to say..but the following probably fits....;
and if you want each string to be a single element of a 2d array..then just replace the 'char's in first reply with 'std::string'Code:std::string m[50]; std::getline(std::cin,m[x]); //where x <50
and the cin ' line with the getline function..
Is there any advantage of initially allocating the size of a std::vector ?.. I have always used std::vector:: push_back(..); when in need of new space..std::vector<std::vector<int>> vec(std::vector(b), a);
Last edited by manasij7479; 04-19-2011 at 06:24 AM. Reason: .. :[b]:p[/b]ush_back(..); was interpreted rather 'nicely'
There is the advantage of only sizing once if the total number of elements needed can be predicted in advance.
With multiple calls of push_back(), it is necessary to resize the vector. When the new size exceeds the previous size, it is necessary to copy all elements from an old buffer to a new buffer. Apart from multiple calls to dynamically allocate memory, it is necessary to copy all values to a new buffer every time the vector is resized. These involve performance hits, particularly if copying individual elements is expensive, and increased chances of memory fragmentation (in the executing process, not the vector).
Implementations of vector can reduce the overhead of repeatedly growing the vector using different strategies (allocating more memory than needed in anticipation of growth, and then not resizing actual buffers for the next few elements push_back'd). No such strategy can beat initialisation with a required size, as that involves resizing the buffer exactly once.
..how is the above process done in a dynamically allocated array ?...i.e when more space is needed...
Is it also completely copied over?