如何訪問元素從myVector
像我將與陣列(for(i = 0; i < n; i++) cout << v[i] << " ";
)C++向量訪問元素
我的代碼:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Month
{
public:
char *name;
int nr_days;
Month(char* c, int nr) : name(c), nr_days(nr){};
~Month() { /* free(name); */}
};
int main()
{
Month January("January", 31);
Month February("February", 28);
Month March("March", 31);
Month April("April", 30);
Month May("May", 31);
Month June("June", 30);
Month July("July", 31);
Month August("August", 31);
Month September("September", 30);
Month Octomber("Octomber", 31);
Month November("November", 30);
Month December("December", 31);
vector<Month> *myVect = new vector<Month>;
myVect->push_back(January);
myVect->push_back(February);
myVect->push_back(March);
myVect->push_back(April);
myVect->push_back(May);
myVect->push_back(June);
myVect->push_back(July);
myVect->push_back(August);
myVect->push_back(September);
myVect->push_back(Octomber);
myVect->push_back(November);
myVect->push_back(December);
for(vector<Month>::const_iterator i = myVect->begin(); i != myVect->end(); i++)
{
/*
Month myMonth = i;
cout << myMonth.name << " " << myMonth.nr_days << endl;
*/
}
free(myVect);
return 0;
}
我想成爲像一個foreach算法:foreach(Month in myVect) cout << ...
另一個問題:如果我取消註釋我的行,它爲什麼會在析構函數中給我一個運行時錯誤?
首先,你可能不想讓'myVect'成爲一個*指針*,但是如果你這樣做了,你需要用new來分配。我很驚訝它不會早點崩潰。 – crashmstr
我在想,「新......」在Adam編輯中被刪除了......? – crashmstr
@crashmstr:就是這樣。爲了羞恥亞當,爲了羞恥...... –