Easy STL question

Started by
4 comments, last by MagTDK 21 years, 7 months ago
This should be an easy question to answer. For some reason I can''t get it to work. How can I declare a function to accept a stl list or vector as a parameter of that function. I want it so I can still retain all of the functionality of a list or vector within that function.
Advertisement
You mean like this?


    #include <vector>#include <list>#include <algorithm>#include <iostream>#include <iterator>using namespace std;template<typename T>void func(const T& v){	copy(v.begin(), v.end(), ostream_iterator<T::value_type>(cout, "\n"));}int main(){	vector<int> v;	v.push_back(0);	v.push_back(1);	v.push_back(2);	func(v);	list<double> l;	l.push_back(0.0);	l.push_back(1.1);	l.push_back(2.2);	func(l);}    


[edited by - SabreMan on September 14, 2002 4:52:08 AM]

Yeah that''s exactly what I meant.

Thanks SabreMan.
I feel compelled to point out that in 99% of cases, you don''t actually need/want your function to take the container (list/vector). Rethink your algorithm, and decide if you can get by with a pair of iterators. Look at the algorithms in STL -- tons of them, and not a single one requires a container to be passed in. There are advantages to working this way -- each of the iterator abstractions are very well defined, and your code will support things like C arrays via pointers. Of course, I could be wrong, you might need the container, but I highly doubt it. Something to think about...
Well, back_inserter takes a container
But I think all algorithms take iterators, as you meant.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Yeah... there are a few things that can only be done if you have the actual container, such as when you want to take things out of the container. But where possible, use an iterator range instead.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions | Organising code files | My stuff ]

This topic is closed to new replies.

Advertisement