PDA

Click to See Complete Forum and Search --> : vector<int>


Knowledge_is_Et
Jun 23rd, 2002, 03:06 PM
Ok, I am trying out www.topcoder.com

I can do classes well enough, and i'm pretty sure (despite my inexperience) that I can code some solutions there. The problem is, for almost every problem that I have an idea of how to solve they are passing a parameter vector<int> . What is this, and how do I use it?

HarryW
Jun 23rd, 2002, 03:50 PM
vector is a template class that is part of the C++ standard library. A vactor object is basically used as an array. Its interface is the same as an array, but with some added member functions that let you do some cool stuff.

The benefit of using a vector rather than an array is that it's easier to use. You don't have to worry about memory allocation when you want to resize the array.

I don't know if you know anything about templates, I'm guessing not if vector<int> doesn't make much sense to you. vector<int> means a vector of integers, a lot like an array of integers. You can put the type for the template to use in the angled brackets.

Knowledge_is_Et
Jun 23rd, 2002, 03:56 PM
if a vector<int> or a vector <string> was passed, how could I use the data?

HarryW
Jun 23rd, 2002, 04:01 PM
I haven't used them myself so I don't know the specific interface, but I know what they do and what they're for. You can use them just like you would an array, ie:

something = aVectorObject[x];

There's probably a member function that tells you the number of elements in the vector too.

parksie
Jun 23rd, 2002, 05:49 PM
As Harry says, a vector is a resizeable array.

It falls under the class of Standard Template Library templates called the containers. These are things like vector, list, deque. The stack template is an adaptor over one of the containers to enforce using push/pop rather than implementing it all itself (it usually uses deque<>).

All these containers support a usage pattern of iterators. This means that you can do the following:vector<int> v;

// add stuff to v

for(vector<int>::iterator i = v.begin(); v != v.end(); ++v) {
cout << *v << endl;
}If you think this looks like some kind of smart pointer, then you're right. The main advantage, is that they're the same across everything; for example you could replace vector with list there, and the functionality would be the same (obviously, the performance traits would differ in line between linked lists and "arrays").

This means that you can code up all sorts of cool generic algorithms, for example, the library provides "copy":copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));...this would print all the elements in v. Note that the container type isn't given - if v was silently altered to use a list, the compiler would resolve the templates out :)



Wow....long post there ;)