rub*_*nvb 9 c++ stl vector append
我完全理解这个问题已经被问了很多,但我要求一个特定的变化,我的搜索foo已经放弃了,因为我只发现了一个算法将一个现有的向量附加到另一个,但没有一个返回到一个功能.
我有这个功能列出目录中的所有文件:
vector<string> scanDir( const string& dir )
Run Code Online (Sandbox Code Playgroud)
可以在内部调用自己(对于子目录).
我需要一种将返回值附加到调用者向量的简短方法.我脑子里有这样的东西(当然它不存在:():
vector<string> fileList;
//...
fileList.append( scanDir(subdirname) );
Run Code Online (Sandbox Code Playgroud)
我担心存储返回值并将其插入fileList会带来性能不佳.我的意思是:
vector<string> temp( scanDir(subdirname) );
copy( temp.begin(), temp.end(), back_inserter(fileList) );
Run Code Online (Sandbox Code Playgroud)
谢谢!
PS:我不是强迫自己使用矢量,任何其他同样表现良好的容器,并且可以阻止潜在的大型复制操作.
Phi*_*ipp 15
为什么不把矢量作为参数传递?然后每个调用都可以附加到同一个向量,而无需复制.或者创建一个实现类,将元素累积到成员对象中.
Mar*_*ner 10
如果您正在进行更改scanDir,请将其作为接受输出迭代器的(模板)函数:
template <class OutIt>
void scanDir(const std::string& dirname, OutIt it) {
// ...
// Scan subdir
scanDir(subdir, it);
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以获得额外的好处,以便能够填充所有类型的数据结构
std::vector<string> vector;
scanDir(dir1, std::back_inserter(vector));
std::set<string> fileset
scanDir(dir1, std::inserter(fileset, fileset.begin()));
Run Code Online (Sandbox Code Playgroud)
等等
编辑(见评论......)
要使用此函数进行类成员初始化,您可以在构造函数中调用它,如同
class MyClass {
private:
std::vector<string> m_fileList;
public:
MyClass(const std::string& dirname) {
scanDir(dirname, std::back_inserter(m_fileList);
}
}
Run Code Online (Sandbox Code Playgroud)
或使用包装函数
std::vector<string> scanDir(const std::string& dirname) {
std::vector<string> result;
scanDir(dirname, std::back_inserter(result);
return result;
}
class MyClass {
// Same as above..
MyClass(const std::string& dirname) : m_fileList(scanDir(dirname)) { }
}
Run Code Online (Sandbox Code Playgroud)
性能(和其他)原因我更喜欢第一个版本...
PS:我不是强迫自己使用矢量,任何其他同样表现良好的容器,并且可以阻止潜在的大型复制操作.
好吧,如果您使用list并打电话,a.splice(a.end(), b);您将完全避免复制操作.A list通常是链接列表而不是数组vector,因为它具有很多性能和使用含义.但是拼接在O(1)中运行,所以这是一个很好的好处.
| 归档时间: |
|
| 查看次数: |
3244 次 |
| 最近记录: |