+ Reply to Thread
Results 1 to 3 of 3

Thread: Should I use arrays or containers of STL like vector?

  1. #1

    Should I use arrays or containers of STL like vector?

    Hi All,

    I am C language guy.

    Now I am moving to C++ world.

    I find it interesting. I have a question about using array or std::vector.

    Which is better and more safe?

    Please help

  2. #2
    Junior Member
    Join Date
    Apr 2012
    In C++, you should always prefer vector instead of array.

    vector is a dynamic array which size increases as you push items into it.

    vector has lot member which offers great services and functionality. If you use array instead, you will need to code on your own those functionality.

    Also it is more safe as described below:

    void UseNameWithArray(char *pName)
    void UseArray()
    	char *pName = new char[100] ;
    	strcpy(pName, "MARK") ;
    	//PART 1: if UseName throws an exception then delete []pName will not get execute.
    	//Hence, memory leak!
    	UseNameWithArray(pName) ;
    	delete [] pName ;
    	pName = NULL ;
    void UseNameWithVector(std::vector<char>& vName)
    void UseVector()
    	std::vector<char> vName ;
    	vName.push_back('M') ;
    	vName.push_back('A') ;
    	vName.push_back('R') ;
    	vName.push_back('K') ;
    	//PART 2: if UseNameWithVector throws an exception then vName will delete the memory allocated in its destructor!
    	UseNameWithVector(vName) ;

  3. #3
    Great example.

+ Reply to Thread

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts