students[i] = pos;
,因爲你要複製的Student
迭代器引用,而不是迭代器本身應改爲
students[i] = *pos;
。
但爲什麼動態數組的Student
而不是std::vector<Student>
?目前,你有內存泄漏,因爲你不delete[] students;
編輯1
刪除。
編輯2
除此之外,所有我可以看到它的錯誤在於
sort (students, students+section.getNumberOfStudents());
這個前提是在不使用任何定製sort
方法前丟失std::
。
編輯3
這裏快要出軌:
students[i] = *pos;
份學生從list
到動態數組students
。這可能是昂貴的,所以這裏是一個另類:
首先證明了這一點,需要的點點滴滴:必需包括
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <functional>
最小的學生類
class Student
{
std::string name;
public:
Student(std::string inname):name(inname)
{
}
const std::string & getname() const
{
return name;
}
friend bool operator<(const Student & a, const Student &b)
{
return a.name < b.name;
}
};
最小科類
class Section
{
public:
std::list<Student> students;
};
最小外運算子
std::ostream& operator<<(std::ostream& out, const Section& section)
{
A std::vector
而不是一個數組和一個常量引用的向量,所以我們不必複製學生。
std::vector<std::reference_wrapper<const Student>> students;
將參考文獻存儲在vector
中。大概可以用std::copy
和std::back_inserter
做一個班輪,但是這對於一個例子來說有點過分了。
for (const auto & student: section.students)
{
students.push_back(std::ref(student));
}
排序vector
std::sort(students.begin(), students.end());
打印的vector
for (const auto & student: students)
{
out << student.get().getname() << " ";
}
return out;
}
和一個main
來統治他們在黑暗中綁定他們
int main()
{
Section s;
s.students.emplace_front("Tom");
s.students.emplace_front("Dick");
s.students.emplace_front("Harry");
std::cout << s;
}
,盡在其中易切正貼塊:
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <functional>
class Student
{
public:
std::string name; // this is me being lazy. name should be private
Student(std::string inname):name(inname)
{
}
const std::string & getname() const
{
return name;
}
friend bool operator<(const Student & a, const Student &b)
{
return a.name < b.name;
}
};
class Section
{
public:
std::list<Student> students;
};
std::ostream& operator<<(std::ostream& out, const Section& section)
{
std::vector<std::reference_wrapper<const Student>> students;
// store references in the `vector`.
for (const auto & student: section.students)
{
students.push_back(std::ref(student));
}
// Sort the `vector`
std::sort(students.begin(), students.end());
// print the `vector`
for (const auto & student: students)
{
out << student.get().getname() << " ";
}
return out;
}
int main()
{
Section s;
s.students.emplace_front("Tom");
s.students.emplace_front("Dick");
s.students.emplace_front("Harry");
std::cout << s;
}
或者做什麼雷米建議,並使用std::vector<Student *>
和一個自定義比較取消引用指針std::sort
。
新列表類型沒有公開方法逐元素訪問? –
我想我有答案,但我刪除它,直到我可以確認'section.students.begin()'返回'std :: list :: Iterator'。 –
user4581301
'section'是const,所以你可能需要'section.students.cbegin()'和'section.students.cend()'。 – kfsone