Hi guys I wonder, what are vectors?? Are they some kind of dynamic-sized arrays??
Cheers,
Adrian.
Vectors
Re:Vectors
In C++, yes. The std::vector class is effectively a resizable array.
You can do this:
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
How come it remembers it's an int?
Cheers
Does this use the RTTI by any chance? I'll need to see the source when I have more time.std::vector<int> v;
Cheers
Re:Vectors
No, std::vector is a templated class:
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.
Code: Select all
template<typename T> vector
{
// ...
}
Re:Vectors
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.
Cheers,
Adrian.
Re:Vectors
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
Hm, but it seems for me templates could create huge code
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
Code: Select all
some-template-definition MyTemplate(var)
{
do-huge-computations-which-take-many-kbs-in-object-file
}
Cheers,
Adrian
Re:Vectors
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.