+ Reply to Thread
Results 1 to 2 of 2

Thread: How to call a function for every element of a C++ stl vector?

  1. #1

    How to call a function for every element of a C++ stl vector?

    How to call a function for every element of a C++ stl vector?

    Below is my example:

    Code:
    void StandardVector()
    {
    	std::vector<char> vName ;
    
    	vName.push_back('M') ;
    	vName.push_back('A') ;
    	vName.push_back('R') ;
    	vName.push_back('K') ;
    
    	std::vector<char>::iterator itr = vName.begin() ;
    	for(; itr != vName.end(); itr++)
    	{
    		char szTemp[100] ; 
    		sprintf(szTemp, "Char : %c\n", *itr) ;
    		OutputDebugString(szTemp) ;
    	}
    }

  2. #2
    You can use std::for_each with custom predicate.

    Example:

    Code:
    void PrintCharacter(char ch)
    {
    	char szTemp[100] ; 
    	sprintf(szTemp, "Char : %c\n", ch) ;
    	OutputDebugString(szTemp) ;
    }
    
    void StandardVector()
    {
    	std::vector<char> vName ;
    
    	vName.push_back('M') ;
    	vName.push_back('A') ;
    	vName.push_back('R') ;
    	vName.push_back('K') ;
    
    	std::for_each(vName.begin(), vName.end(), PrintCharacter) ;
    }
    Hope this helps.

+ Reply to Thread

Tags for this 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