### How to print from a vector?

How to print from this vector?

 ``12345`` `````` //Cars vector ParkingLot; ParkingLot.push_back(Car(234, 4, 2, EColor::NOCOLOR, "Sibble")); ParkingLot.push_back(Car(457.1, 4, 4, EColor::PURPLE, "Sal")); ParkingLot.push_back(Car(3423.8, 4, 3, EColor::BLUE, "Susan"));``````

I thought this:
cout << Car.ParkingLot(0);
but it doesn't work. Any body know?
Last edited on
 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include #include #include using namespace std; int main() { vector numbers; numbers.push_back(rand() % 100); numbers.push_back(rand() % 100); numbers.push_back(rand() % 100); cout << "\none\n"; for (unsigned int i=0; i::iterator it = numbers.begin(); it!=numbers.end(); it++) { cout << *it << endl; } cout << "\nthree\n"; for ( auto n : numbers) { cout << n << endl; } }``````

Output:
 ``` one 41 67 34 two 41 67 34 three 41 67 34 ```
The simple way, print from vector<Car>:

 ``123456789101112`` ``````std::ostream& operator<<(std::ostream& os, const std:vector& vc) { os << '['; for (auto itr = vc.cbegin(); itr != vc.cend(); ++itr) { if (itr != vc.cbegin()) os << ','; os << *itr; } os << ']'; return os; }``````

Slightly more complex, use template to print from vector of any class:

 ``123456789101112`` ``````template std::ostream& operator<<(std::ostream& os, const vector& v) { os << '['; for (auto itr = v.cbegin(); itr != v.cend(); ++itr) { if (itr != v.cbegin()) os << ','; os << *itr; } os << ']'; return os; }``````

And more complex, use template to print from any collection of any class.
 ``123456789101112`` ``````template < template class C, class T> std::ostream& operator<<(std::ostream& os, const C >& c) { os << '['; for (auto itr = c.cbegin(); itr != c.cend(); ++itr) { if (itr != c.cbegin()) os << ','; os << *itr; } os << ']'; return os; }``````

But, more accurately, any collection with two template class parameters such as list and vector, and not map, multimap, set and multiset.
Refer:
http://www.cplusplus.com/reference/list/list/
http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/reference/map/map/
http://www.cplusplus.com/reference/map/multimap/
http://www.cplusplus.com/reference/set/set/
http://www.cplusplus.com/reference/set/multiset/

In all cases you have to provide a streaming operator for your class Car:

 ``12345678`` ``````std::ostream& operator<<(std::ostream& os, const Car& car) { os << '(' << car.cost << ',' << car.wheels << ',' << car.doors << ',' << car.color << ',' << car.make << ')'; // obviously change to suite return os; }``````

Topic archived. No new replies allowed.