cawte potreboval by som poradit ako v C++ realokovat pamat neco ako realloc() v C ;)
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Data {
string sub;
struct Greats {
vector<string> def;
};
Greats greats;
};
int main() {
enum { ALLOC = 100, STEP = 10 };
// alokuje pamat
Data *data = new Data[ALLOC];
for (int i=0; i < ALLOC; i++) {
data[i].sub = "sub";
// zmaze vsetku pamat a nahradi ju novou vacsou...
// ako to zmenit, aby ju len rozsirilo?
data = new Data[ALLOC + STEP];
cout << i << ". " << data[i].sub;
for (int j=0; j < STEP; j++) {
data[i].greats.def.push_back("def");
cout << " : " << data[i].greats.def[j];
}
cout << endl;
}
delete [] data;
}
alebo mam si nastudovat STD alokatory?
cize ked napisem
// main()
vector<Data> data;
ako budem vkladat data do poloziek vnorenej struktury?
alebo data[47].greats.def.push_back("23") -- prida na koniec pola def 23.
Alebo si sa pytal nieco ine?:-)
Mozno otazka, naco si definoval triedu greats? def si mohol rovnako definovat vo vnutri triedy ako vector<string>
trieda Data ......--> string subject;
..............->array[real] mark; // ulozenie znamok ktore patria subject
..............->array[string] def; // popis kazdej znamky
++ neake metody na vypocet napr priemeru atd
no toto asi bez vnorenej neurobim :-D
P.S. ten tvoj sposob nefunguje skusal som toto:
vector<Data> data;
data[0].sub = "math";
cout << data[0].sub << endl;
C++ vyvola vynimku Segmentation fault...proste potrebujem asi neco takehoto:
data.push_back().sub = "string"
data.push_back().greats.def.push_back("string");
Na zaciatku ma nulovu velkost (prazdne pole).
T.resize(47) ho zvacsi na velkost 47
T.push_back(a) vlozi na koniec prvok a;
Segfault ti spravil preto, lebo to pole ma velkost 0 pristupujes niekam, kam nemas...
spravne by malo byt data.sub.push_back("math")
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Data {
string sub;
struct Greats {
vector<string> def;
};
Greats greats;
};
int main() {
vector<Data> data;
data.resize(100);
// data.sub.push_back("string"); nefunguje....
data[0].sub = "string";
data[0].greats.def.push_back("def");
cout << data[0].sub << endl;
cout << data[0].greats.def[0] << endl;
}