为什么使用STL复制算法会出现"passing 'const Person' as 'this' argument discards qualifiers"?
Why does appear "passing 'const Person' as 'this' argument discards qualifiers" while using STL copy algorithm?
我正在尝试在用户定义的结构上实现最大堆,并且我使用 std::copy_n()
算法从 heap.in
文件中获取输入,但我从编译器收到此类错误:
passing 'const Person' as 'this' argument discards qualifiers
谁能告诉我问题出在哪里?
#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;
}
我猜你是这个意思
int main () {
fin >> n;
std::copy_n (std::istream_iterator <Person> (fin), n, std::back_inserter(Heap));
return 0;
}
std::copy_n
将 n 项从第一个参数复制到第三个参数。如果要附加到矢量,则必须使用包装器 std::back_inserter
,因为 std::copy_n
不会自行增加矢量的大小。
我正在尝试在用户定义的结构上实现最大堆,并且我使用 std::copy_n()
算法从 heap.in
文件中获取输入,但我从编译器收到此类错误:
passing 'const Person' as 'this' argument discards qualifiers
谁能告诉我问题出在哪里?
#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;
}
我猜你是这个意思
int main () {
fin >> n;
std::copy_n (std::istream_iterator <Person> (fin), n, std::back_inserter(Heap));
return 0;
}
std::copy_n
将 n 项从第一个参数复制到第三个参数。如果要附加到矢量,则必须使用包装器 std::back_inserter
,因为 std::copy_n
不会自行增加矢量的大小。