+ Reply to Thread
Results 1 to 2 of 2

Thread: Using std::vector container in C++.

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    29

    Using std::vector container in C++.

    Hi All,

    Can anyone provide useful information on using std::vector container in C++?

    Thanks

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hello,

    std::vector is a template class and holds item of specified type.

    It is sequence container and can grow dynamically.

    Example:

    Code:
    #include <vector>
    #include <string>
    #include <iterator>
    #include <algorithm>
    
    void UseVector()
    {
    	//vector holds item of specified type.
    	//vector is a dynamic array, that is vector can grow dynamically when there is no space for more elements.
    	typedef std::vector<std::string> STRING_VECTOR_TYPE ;
    
    	STRING_VECTOR_TYPE vStrings ;
    
    	vStrings.push_back("One") ;
    	vStrings.push_back("Two") ;
    	vStrings.push_back("Three") ;
    	vStrings.push_back("Four") ;
    	vStrings.push_back("Five") ;
    
    	//we need const_iterator type to iterate throgh the vector items
    	char szName[100] ;
    	STRING_VECTOR_TYPE::const_iterator constItr = vStrings.begin() ;
    	for(; constItr != vStrings.end() ; constItr++)
    	{
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//we need iterator type to iterate through the vector items and delete the item...
    	STRING_VECTOR_TYPE::iterator itr = vStrings.begin() ;
    	for(; itr != vStrings.end() ;)
    	{
    		if("Three" == *itr)
    		{
    			itr = vStrings.erase(itr) ;
    		}
    		else
    		{
    			 ++itr ;
    		}
    	}
    
    	//iterate through vector items again...
    	constItr = vStrings.begin() ;
    	for(; constItr != vStrings.end() ; constItr++)
    	{
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//find a specified item from vector
    	//oops, vector does not have find member!
    	constItr = std::find(vStrings.begin(), vStrings.end(), "Four") ;
    	if(constItr != vStrings.end())
    	{
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//delete all the items from vector...
    	vStrings.clear() ;
    }
    Note:
    a. std::vector are good at accessing element from their position.
    b. Add and remove element from their end.

+ Reply to Thread

Bookmarks

Posting Permissions

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