在我的代碼中,我有一個Student對象的向量。在C++中,如何在保持指向對象的指針的同時將對象推入矢量?
vector<Student> m_students;
我想:看到
- 檢查載體含有一定名稱的任何學生。
- 如果沒有這樣的學生存在,添加一個新的。
- 將數據添加到該名稱的學生。
考慮下面的代碼:
// Check to see if the Student already exists.
Student* targetStudent = NULL;
for each (Student student in m_students)
{
if (student.Name() == strName)
{
targetStudent = &student;
break;
}
}
// If the Student didn't exist, add it.
if (targetStudent == NULL)
{
targetStudent = new Student(strName);
m_students.push_back(*targetStudent);
}
// Add the course info to the Student.
targetStudent->Add(strQuarter, strCourse, strCredits, strGrade);
當我撥打電話到m_students.push_back(*targetStudent);
似乎矢量「m_students」結束了Student對象的副本「targetStudent」指向那個時間。
隨後嘗試添加到targetStudent不會更改向量中包含的對象。
我該如何從一個指向對象的指針開始,將該對象添加到一個矢量,然後訪問該矢量中的對象?
我會建議在引用標準名稱空間時總是使用:: std而不是std。如果有人曾經自己創建了名爲'std'的命名空間(當然不是頂級的,那將是不合法的),那麼在某些情況下,最終可能會出現含糊不清或意外解決的std引用。 – Omnifarious 2009-10-12 04:25:01
@Omnifarious有些人也可能會做'#define std foo'。你無法準備那裏的每一個白癡。 – 2012-03-23 23:06:03
@quant_dev:這不是因爲有人可能在另一個命名空間內創建名爲'std'的命名空間。這是因爲你總是習慣於用你指的名字來引用命名空間,而不是今天似乎工作的最方便的名稱。 – Omnifarious 2012-03-23 23:16:57