c++stlcopyistream-iterator

Why does appear "passing 'const Person' as 'this' argument discards qualifiers" while using STL copy algorithm?


I'm trying to implement a max heap on user defined structures, and I use the std::copy_n() algorithm to take input from heap.in file, but I receive this kind of error from the compiler:

passing 'const Person' as 'this' argument discards qualifiers

Can anyone tell me where the issue is?

#include <fstream>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <functional>
#include <iterator>
#include <string>
#include <iostream>


std::ifstream fin ("heap.in");
std::ofstream fout ("heap.out");

struct Person {
    int age;
    std::string name;

    bool operator < (const Person p) const{
        if (this->age != p.age)
            return this->age < p.age;
        return this->name < p.name;
    }

    friend std::istream& operator >> (std::istream& flux, Person& p) {
        flux >> p.name >> p.age;
        return flux;
    }

    friend std::ostream& operator << (std::ostream& flux, Person p) {
        flux << "(" << p.name << ", " << p.age << "); ";
        return flux;
    }

    friend std::ifstream& operator >> (std::ifstream& flux, Person& p) {
        flux >> p.name >> p.age;
        return flux;
    }

    friend std::ofstream& operator << (std::ofstream& flux, Person p) {
        flux << "(" << p.name << ", " << p.age << "); ";
        return flux;
    }
};

int n;
std::vector <Person> Heap;

int main () {
    fin >> n; 
    std::copy_n (Heap.begin (), n, std::istream_iterator <Person> (fin));
    return 0;
}

Solution

  • I guess you meant this

    int main () {
        fin >> n;
        std::copy_n (std::istream_iterator <Person> (fin), n, std::back_inserter(Heap));
        return 0;
    }
    

    std::copy_n copies n items from it's first argument to it's third. If you want to append to a vector then you must use the wrapper std::back_inserter as std::copy_n won't increase the size of the vector by itself.