-
May 30th, 2012, 04:56 AM
#1
Vectors and Arrays
Is there a difference between vectors and Arrays? If I know arrays well and I can deal with them dynamically, do I have also to know about vectors ?
-
May 30th, 2012, 05:01 AM
#2
Re: Vectors and Arrays
Originally Posted by ahmed_sobhy
Is there a difference between vectors and Arrays? If I know arrays well and I can deal with them dynamically,
You must be using another computer language. In C++, arrays are not dynamic.
Regards,
Paul McKenzie
-
May 30th, 2012, 05:04 AM
#3
Re: Vectors and Arrays
In c++, I can use pointers with arrays to allocate memory dynamically. Am I true ? So what are vectors for ?
-
May 30th, 2012, 05:07 AM
#4
Re: Vectors and Arrays
Originally Posted by ahmed_sobhy
In c++, I can use pointers with arrays to allocate memory dynamically. Am I true ?
You are not "true".
An array is not a pointer. A pointer is not an array. An array in C++ has a specific definition:
That is an array. Now how do you dynamically change the size of it in C++? You can't.
That's what vectors are for -- a vector can be dynamically resized.
Regards,
Paul McKenzie
-
May 30th, 2012, 05:12 AM
#5
Re: Vectors and Arrays
Secondly, as far as dynamically allocated memory and pointers are concerned, here is the issue with them:
Code:
class foo
{
private:
char *ptr;
public:
foo()
{
ptr = new char [10];
}
~foo()
{
delete [] ptr;
}
};
int main()
{
foo x;
foo y = x;
} // double deletion error -- deleting the same address twice!
Fix the bug in this program using dynamically allocated memory and pointers. Once you do that, then you will see why vector is much more powerful and easier to use then raw pointers and dynamically allocated memory.
Regards,
Paul McKenzie
Last edited by Paul McKenzie; May 30th, 2012 at 05:14 AM.
-
May 30th, 2012, 05:17 AM
#6
Re: Vectors and Arrays
Thank you a lot for your help. It seems I will get to know more about vectors.
-
May 30th, 2012, 06:16 AM
#7
Re: Vectors and Arrays
Originally Posted by ahmed_sobhy
It seems I will get to know more about vectors.
It's important to know all main containers of the C++ standard library. That includes vector of course but also list, deque, set, map, unordered_set and unordered_map as well as array (which is not the same as the language level array).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|