Print STL
How I can to create an ostream operator << in this case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
using std::vector;
class lista {
public:
int number;
string name;
};
vector<lista> telephonelist;
void inclusao() {
lista e;
int n;
string name, number;
cout << "Input the number of contacts: " << endl;
cin >> n;
for (int i = 0; i < n; i++) {
cout << "Input the name: " << endl;
cin >> e.name;
cout << "Input the number: " << endl;
cin >> e.number;
telephonelist.push_back(e);
}
}
bool ordenaAux(lista playerObj, lista playerObj2) {
return playerObj.name < playerObj2.name;
}
void ordena() {
sort(telephonelist.begin(), telephonelist.end(), ordenaAux);
}
int main() {
vector<lista> telephonelist;
inclusao();
ordena();
for (unsigned i = 0; i < telephonelist.size(); ++i) {
cout << telephonelist[i] << endl;
}
}
|
Are you trying to overload
operator<< so a vector can be inserted into the output stream as easily as a regular data type, say an
int?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <vector>
#include <string>
template <typename T>
std::ostream& operator<<(std::ostream&, const std::vector<T>&);
int main()
{
std::vector<int> ivec { 3, 5, 10, 6, 14, 99, 128 };
std::cout << ivec << "\n\n";
std::vector<std::string> svec { "One", "Two", "Three", "Four", "Five" };
std::cout << svec << '\n';
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
{
for (auto const& x : v)
{
os << x << ' ';
}
return os;
}
|
3 5 10 6 14 99 128
One Two Three Four Five |
I created the function as a template overload so any data type that can use
std::cout can use the overload.
Even a custom class as long as you have an
operator<< overload to print any data members the class contains.
Topic archived. No new replies allowed.