I fully understand this question has been asked a lot, but I’m asking for a specific variation and my search-foo has given up, as I’ve only found algorithms that append one existing vector to another, but not one returned to from a function.
I have this function that lists all files in a directory:
vector<string> scanDir( const string& dir )
which may call itself internally (for subdirectories).
I need a short way of appending the returned value to the caller’s vector. I have in my mind something like this (but of course it doesn’t exist 🙁 ):
vector<string> fileList;
//...
fileList.append( scanDir(subdirname) );
I fear that storing the return value and inserting it in fileList would bring performance badness. What I mean is this:
vector<string> temp( scanDir(subdirname) );
copy( temp.begin(), temp.end(), back_inserter(fileList) );
Thanks!
PS: I’m not forcing myself to using vector, any other container that performs equally well and can prevent the potential large copy operation is fine by me.
If you’re in the position to change
scanDir, make it a (template) function accepting an output iterator:You’ll have the additional benefit to be able to fill all sort of data structures like
etc.
EDIT (see comment …)
For using this function for class member initialization, you could either call it in the constructor as in
or using a wrapper function
I would prefer the first version for performance (and other) reasons …