Thread: Infinite Arrays?

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    4

    Infinite Arrays?

    How can I make an infinite-size array? I saw something about vector<type> but I'm a bit confused on how to use them... help?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    You can't make an infinite array unless you have infinite memory. But you can use a container that grows as needed:
    Code:
    #include <iostream>
    #include <vector>
    
    int main()
    {
      std::vector<int> v; // Define a vector of int called v
    
      // Append 10 values to the vector
      for (int i = 0; i < 10; i++)
        v.push_back(i);
    
      // Print out all elements of the vector
      for (int i = 0; i < v.size(); i++)
        std::cout<< v.at(i) <<'\n';
    }
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    May 2005
    Posts
    4
    Thanks!

    Question: Is there any way to use those with structs? Like vector<struct> or something?

  4. #4
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    you can have any type in a vector, including another vector

  5. #5
    Registered User
    Join Date
    May 2005
    Posts
    4
    Well, by this, I mean like having multiple structs. You know, like:

    Code:
    struct blah_struct[] {
    int blah_var;
    } blah[10]
    How would I have a vector replace the blah[10]?

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    In your example the type of your structure is blah_struct. Just replace int with the name of your type:
    Code:
    #include <iostream>
    #include <vector>
     
    struct blah_struct {
    int blah_var;
    };
     
    int main()
    {
      // Define a vector of blah_struct called v starting with 10 objects.
      std::vector<blah_struct> blah_vector(10);
     
      // Print out all elements of the vector
      for (int i = 0; i < blah_vector.size(); i++)
    	std::cout<< blah_vector.at(i).blah_var <<'\n';
    }
    If your struct is not a simple one with only POD objects, you'll have to be careful about using it in a container. It might need a copy constructor and copy assignment operator.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. My Arrays!!!, My Arrays!!! Help!?
    By llcool_d2006 in forum C++ Programming
    Replies: 1
    Last Post: 12-10-2006, 12:07 PM
  4. Need Help With 3 Parallel Arrays Selction Sort
    By slickwilly440 in forum C++ Programming
    Replies: 4
    Last Post: 11-19-2005, 10:47 PM
  5. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 09:24 PM