Re: Embarrassing problem with vector
In article <bdd527f1-dada-41d8-8ddd-
53943b85283c@g31g2000yqc.googlegroups.com>, tuo_pe@yahoo.com says...
template<typename T>
void PrintVector(const vector<T> &vec)
{
vector<T>::const_iterator cur = vec.begin();
while (cur != vec.end()) {
cout << *cur << ", ";
++cur;
}
cout << endl;
}
Now that you've got your original problem figured out, consider using
std::copy instead of the explicit loop:
template <class T>
void PrintVector(const vector<T> &vec) {
copy(vec.begin(), vec.end(),
ostream_iterator<T>(cout, ", "));
cout << endl;
}
Of course, you probably don't really want the ", " after the last
element, in which case you'd want to replace the ostream_iterator
with the infix_ostream_iterator that was posted here a few months
ago. There's also little real reason to restrict the function to
working with a vector -- it could just as well work with any
collection that provides 'begin()' and 'end()' member functions:
#include <vector>
#include <algorithm>
#include <iostream>
#include "infix_iterator.h"
template <class Coll>
void PrintColl(const Coll col) {
std::copy(col.begin(), col.end(),
infix_ostream_iterator<typename Coll::value_type>
(std::cout, ", "));
std::cout << std::endl;
}
int main() {
std::vector<int> vec;
for (int i=0; i<16; i++)
vec.push_back(i);
PrintColl(vec);
return 0;
}
Result:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
--
Later,
Jerry.