none
iterating through and matching a vector array RRS feed

  • Question

  • hi im trying to iterate through a vector array and seeing if 

    there is a match between two strings

     

    is this the correct way to iterate through a vector array

    thanks alot

     

    std::vector<char*> Names;
    
    	std::vector <char*>::iterator It;
    
    Names.push_back("hello");
    Names.push_back("how");
    Names.push_back("are");
    Names.push_back("you");
    
    
    // iterate through vectors
    
    			for (It = Names.begin(); It != Names.end(); ++It)
    
    			{
    
    				// erase field
    
    				if(*It == "are")
    
    				{
    
    					Names.erase(It);
    
    				}
    
    
    
    			}

    Saturday, March 27, 2010 3:47 AM

Answers

  • It is the correct way to iterate through a vector.

    But your code inside the loop has a couple of problems.  Your comparison is comparing pointers, not comparing character strings.  If you are learning vector why not learn std::string as well.  With std::string you can compare character strings with ==.

    When you erase an element from a vector the iterator becomes obsolete.  So don't keep iterating with it.

     

    • Marked as answer by Nz tribute Saturday, March 27, 2010 4:49 AM
    Saturday, March 27, 2010 4:25 AM

All replies

  • It is the correct way to iterate through a vector.

    But your code inside the loop has a couple of problems.  Your comparison is comparing pointers, not comparing character strings.  If you are learning vector why not learn std::string as well.  With std::string you can compare character strings with ==.

    When you erase an element from a vector the iterator becomes obsolete.  So don't keep iterating with it.

     

    • Marked as answer by Nz tribute Saturday, March 27, 2010 4:49 AM
    Saturday, March 27, 2010 4:25 AM
  • thanks

    what about strcmp() if i do something like this.

     

    std::vector<char*> Names;
    
    	std::vector <char*>::iterator It;
    
    Names.push_back("hello");
    Names.push_back("how");
    Names.push_back("are");
    Names.push_back("you");
    
    
    // iterate through vectors
    
    			for (It = Names.begin(); It != Names.end(); ++It)
    
    			{
    
    				// erase field
    
    				if(strcmp(*It, "are") == 0)
    
    				{
    
    					Names.erase(It);
    					break;
    
    				}
    
    
    
    			}

    Saturday, March 27, 2010 4:33 AM
  • When you erase, use the return value:

    It = Names.erase(It);

    - Wayne

    Saturday, March 27, 2010 4:40 AM
  • There's not really any circumstance where you should have to iterate through an STL container manually. There are plenty of STL algorithms written already that do this sort of thing for you. std::find or std::remove would do nicely here.
    Saturday, March 27, 2010 5:24 AM