Page 1 of 1
Vectors
Posted: Sat Feb 14, 2004 1:55 pm
by Adek336
Hi guys
I wonder, what are vectors?? Are they some kind of dynamic-sized arrays??
Cheers,
Adrian.
Re:Vectors
Posted: Sat Feb 14, 2004 2:07 pm
by Tim
In C++, yes. The std::vector class is effectively a resizable array.
You can do this:
Code: Select all
#include <vector> // std::vector
#include <iostream> // std::cout
#include <algorithm> // std::reverse
int main()
{
std::vector<int> v;
std::vector<int>::iterator it;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
// Print 1 2 3 4
for (it = v.begin(); it != v.end(); ++it)
std::cout << *it;
// Get element 2 = 3
it = v.begin() + 2;
// Remove element 2
v.erase(it);
// Print 1 2 4
for (it = v.begin(); it != v.end(); ++it)
std::cout << *it;
// Reverse the vector
std::reverse(v.begin(), v.end());
// Print 4 2 1
for (it = v.begin(); it != v.end(); ++it)
std::cout << *it;
return 0;
}
Re:Vectors
Posted: Sat Feb 14, 2004 2:56 pm
by Adek336
How come it remembers it's an int?
std::vector<int> v;
Does this use the RTTI by any chance? I'll need to see the source when I have more time.
Cheers
Re:Vectors
Posted: Sat Feb 14, 2004 3:27 pm
by Tim
No, std::vector is a templated class:
Code: Select all
template<typename T> vector
{
// ...
}
When you declare an instance of a template class, the compiler generates a copy of the class specialized to whatever you pass in the template parameters. For instance, std::vector takes a type name (here I used int). So in the example I gave, the compiler generates a specialisation of the std::vector class which can work on ints. The C++ Standard Library, a.k.a. the Standard Template Library, uses templates a lot.
Re:Vectors
Posted: Sat Feb 14, 2004 3:46 pm
by Adek336
WOW
I have to take a look at it! I had a hard time using my blist_t class for binary lists which saved data as void. So many typecasts, and now, if I used templates.... ;D WOW.
Cheers,
Adrian.
Re:Vectors
Posted: Sat Feb 14, 2004 6:30 pm
by Tim
Templates are one of the best features of C++. I've been hacking in C# recently, which lacks templates, and it's a real pain casting from System.Object (aka void*) all the time.
Re:Vectors
Posted: Sun Feb 15, 2004 7:19 am
by Adek336
Hm, but it seems for me templates could create huge code
Code: Select all
some-template-definition MyTemplate(var)
{
do-huge-computations-which-take-many-kbs-in-object-file
}
gets a copy in the output file for each type it is used, fe. ints, chars, shorts etc. Though, if I write a kernel in C++ I already have huge code.. perhaps it won't be a big difference? ::)
Cheers,
Adrian
Re:Vectors
Posted: Sun Feb 15, 2004 9:36 am
by Tim
Yes, there is this possibility. You usually use templates for small classes that you don't mind being duplicated for each set of parameters. The compiler helps by only generating the functions you actually use.