Reputation: 3
I want to store the values of p1 and p2 into vector vip and print vip using the following code:
#include <iostream>
#include <vector>
#include "Person.h"
#include "Daglejer.h"
#include "Funktionaer.h"
using namespace std;
int main() {
Person p1("Mads", 21);
Person p2("Carl", 23);
Person p3("Thomas", 32);
Person p4("Magnus", 8);
Person p5("Joe", 81);
vector <Person>vip;
vip.push_back(p1);
vip.push_back(p2);
vector<Person>::iterator i;
for(i = vip.begin(); i != vip.end(); i++)
cout << vip[i];
return 0;
}
The header file Person.h contains the following:
#ifndef PERSON_H_
#define PERSON_H_
#include <string>
using namespace std;
class Person {
private:
string navn;
int alder;
public:
Person(string, int);
Person();
void setNavn(string);
string getNavn();
void setAlder(int);
int getAlder();
};
#endif /* PERSON_H_ */
and the cpp file:
#include "Person.h"
using namespace std;
Person::Person(){
}
Person::Person(string name, int age) {
setNavn(name);
setAlder(age);
}
void Person::setNavn(string name){
navn = name;
}
void Person::setAlder(int age){
alder = age;
}
string Person::getNavn(){
return navn;
}
int Person::getAlder() {
return alder;
}
When I compile I get the following error:
no match for 'operator[]' (operand types are 'std::vector' and 'std::vector::iterator {aka __gnu_cxx::__normal_iterator >}')
at the line where i use cout. I've searched a lot on stackoverflow and several other websites, but the solutions given didn't solve my problem. I hope someone can help me. Thanks in advance. Mads.
Upvotes: 0
Views: 189
Reputation: 18342
ostream
has no concept of what Person
is supposed to output to. You need to overload the ostream
or reference the field you want specifically.
i.e., either:
cout << i->getNavn() << " " << i->getAlder() << endl;
or
ostream& operator<<(ostream& os, const Person& p)
{
os << p.getAlder() << '--' << p.getNavn() << endl;
return os;
}
Upvotes: 0
Reputation: 1866
You don't need to call the subscript operator when iterating over a list, just dereference the iterator itself.
for(i = vip.begin(); i != vip.end(); i++)
cout << *i;
Additionally you'll either need to add a non-member overload of << to Person, or just call the getters on what you want to display.
for(i = vip.begin(); i != vip.end(); i++)
cout << i->getNavn();
Upvotes: 4