Reputation: 99
I have a complex nested hierachy of objects which I need to filter at output, sucht that only objects which meet certain criteria are written to file.
Suppose I have class A, which comprises an STL vector array of objects B, where each object B comprises an STL vector array of objects C.
Now all the clever stuff has been done and the filtered results need to be written to file:
class A
{
...
std::vector<B> bArray;
std::ostream & filterA(std::ostream &out, int param1,int param2, bool param3)
{
if (param1>0)
{
for (intcurB=0;curB!=bArray.size();curB++)
{
out << bArray.at(curB).filterB(param2,param3);
}
else if (param1<=0) out << "";
return out;
}
};
class B
{
std::vector<C> cArray; std::ostream & filterB(std::ostream &out, int param2, bool param3)
{
if (param2<0)
{
for (int curC=0;curC!=cArray.size();curC++)
{
out << cArray.at(curC);
}
}
else if (param2>0) out << "";
else if(param3) out << "\nInvalid object\n";
else out << "";
return out;
}
};
class C {
bool isSet;
std::vector<int> intArray;
... };
std::ostream & operator <<(std::ostream & out, C &c)
{
if(c.isSet)
{
for (int curInt=0;curInt!=intArray.size();curInt++)
{
out << c.intArray.at(curInt) << " ";
}
out << "\n";
}
else if (!c.isSet) out << "";
return out;
}
int main()
{
A aObject;
....
// Now lets write filtered objects to file
std::ofstream outputFile("/home/user/test.txt");
if (outputFile.is_open())
{
outputFile << aObject.filterA(outputFile,1,-1,false);
outputFile.close();
}
return 0;
}
The code works i.e. it compiles and runs but the address of the ostream object is written to file too!
My questions are
Upvotes: 0
Views: 299
Reputation: 31445
Are you looking for a code-review?
There are a few things I would correct there.
Similarly B as a collection of C, although here it must be a pointer to the vector not a reference as B must be assignable to be in a vector (unlike with A which is not itself a vector element).
You could use an algorithm to loop or BOOST_FOREACH. In any case your looping construct is not the best. Slightly better to use iterators. If you use indexes then size_t or vector::size_type as the index. Better to calculate size() once outside the loop or in the first part of the for eg
for( std::vector<B>::size_type i = 0, len = v.size(); i != len; ++i )
Do not use at(). You know your indexes are not out of bounds. Prefer operator[] if you have to use this construct.
Neither filterA nor filterB modify their classes so make them const member functions.
Streaming empty strings is just pointless code. It's one thing if you have a string variable that might be empty but os << ""
achieves nothing.
Upvotes: 1