Thread: Adding More Array Elements?

  1. #1
    Registered User Vermillion's Avatar
    Join Date
    Aug 2008
    Location
    Bolivia
    Posts
    3

    Adding More Array Elements?

    On PHP, you can add more elements to your array with different methods. My preferred method is:

    PHP Code:
    person[1] = "James";
    person[2] = "Andy";

    person[] = "Nick"//Notice there is no number inside the brackets. That's how I add elements to my arrays on PHP. 
    Can I do something similar with C++? Or how can I add more elements to my arrays?

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Easy... use a std::vector instead of an array.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Closest thing to a PHP associative array in C++ is the Standard Template Library's map container. However, even that requires an actual key, so cpjust is right; for the example you've provided, an STL vector would probably make more sense:
    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    
    int main()
    {
        std::vector<std::string> myArray;
    
        myArray.push_back("James"); 
        myArray.push_back("Andy");
        myArray.push_back("Nick");
    
        for (unsigned int i = 0; i < myArray.size(); ++i)
        {
            std::cout << "Element " << i << ": " << myArray[i] << std::endl;
        }
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. adding elements in array
    By reb221 in forum C Programming
    Replies: 6
    Last Post: 12-30-2008, 02:41 PM
  2. Setting all elements of an array to zero
    By kolistivra in forum C Programming
    Replies: 9
    Last Post: 08-29-2006, 02:42 PM
  3. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  4. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM