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?
Printable View
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?
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';
}
Thanks!
Question: Is there any way to use those with structs? Like vector<struct> or something?
you can have any type in a vector, including another vector ;)
Well, by this, I mean like having multiple structs. You know, like:
How would I have a vector replace the blah[10]?Code:struct blah_struct[] {
int blah_var;
} blah[10]
In your example the type of your structure is blah_struct. Just replace int with the name of your type: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.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';
}