1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using std::vector;
using std::string;
using std::stringstream;
using std::cout;
struct Foo
{
string id;
int type; // 0 ... 2
Foo(string id = "", int type = 0) : id(id), type(type) {}
// Returns string representation of Foo
string ToString()
{
stringstream ss;
ss << "Foo(" << id << "," << type << ", " << std::hex << this << ")";
return ss.str();
}
};
struct Fooz : Foo {};
// Mock of the possible return values for BigBox.getFoo()
struct BigBox
{
bool getFoo(Foo *fillMe) { *fillMe = items[idx++]; return true; }
static int size() { return items.size(); }
static void PrintStaticFooAddresses()
{
cout << "Addresses\n";
for (int i = 0; i < items.size(); i++)
{
cout << "\tFoo(" << items[i].id << "," << items[i].type << ") @ Address: " << std::hex << &items[i] << "\n";
}
}
private:
static int idx;
static vector<Foo> items;
};
vector<Foo> BigBox::items{
Foo("Zero", 0), Foo("ZEro", 0), Foo("ZERo",0), Foo("ZERO",0),
Foo("One", 1),
Foo("Two", 2), Foo("TWo", 2)
};
int BigBox::idx = 0;
BigBox theBigBox; // Singleton
int main()
{
// Show us where Foo objects are allocated
BigBox::PrintStaticFooAddresses();
// Map to fill
vector<Foo> fooMap[3];
// Code snippet in question
for (int i = 0; i < BigBox::size(); i++)
{
Fooz fz;
Foo *pFoo = &fz;
bool success = theBigBox.getFoo(pFoo);
fooMap[pFoo->type].push_back(fz); // analogous to .addToTail()
}
// Did it work?
for (int type = 0; type < 3; type++)
{
cout << "Type[" << type << "]: \n";
for (int i = 0; i < fooMap[type].size(); i++)
{
cout << "\t" << fooMap[type][i].ToString() << "\n";
}
}
}
| |