- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
问题
我有一段旧的 pre-STL C++ 代码,我想在不降低效率的情况下将其转换为 std C++11。
using T = unsigned; // but can be any POD
FILE* fp = fopen( outfile.c_str(), "r" );
T* x = new T[big_n];
fread( x, sizeof(T), big_n, fp );
delete[] x;
fclose( fp );
请注意,big_n 确实很大 - 就像数百万条记录一样大,因此任何低效都会很明显。
先前的解决方案
在此answer根据我之前的问题,我接受了这个解决方案:
std::vector<T> x(big_n);
fread(x.data(), sizeof(T), big_n, fp);
问题和尝试的解决方案
之前的解决方案有效,但构造函数实际上调用了 T 的默认构造函数 big_n 次。当 big_n 真的很大时,这非常慢(而且完全没有必要,因为我即将从磁盘中 fread() 整个 block )。 FWIW,在我对一个文件的测试用例中,它花费了 3 秒而不是 200 毫秒。
所以我试着用这个代替:
std::vector<T> x;
x.reserve( big_n );
fread(x.data(), sizeof(T), big_n, fp);
这似乎可行,但后来我遇到了 size() 返回 0 而不是 big_n 的问题。
如何在不损失太多效率的情况下纠正此问题?
附录
我刚刚注意到 std::vector<>
可以采用自定义分配器。使用这种形式的构造函数可以解决我的问题吗?我现在正在研究这种方法。
什么对我有用
除了 jrok 的简单数组解决方案之外,我还研究了下面 Ali 的自定义分配器解决方案。我决定采用 jrock 的解决方案,因为它易于理解/维护成本较低。
我想出的工作代码如下:
#include <vector>
#include <set>
#include <memory>
#include <fstream>
#include <iostream>
#include <cassert>
struct Foo
{
int m_i;
Foo() { }
Foo( int i ) : m_i( i ) { }
bool operator==( Foo const& rhs ) const { return m_i==rhs.m_i; }
bool operator!=( Foo const& rhs ) const { return m_i!=rhs.m_i; }
friend std::ostream& operator<<( std::ostream& os, Foo const& rhs )
{ os << rhs.m_i; }
};
// DESIGN NOTES /*{{{*/
//
// LIMITATION T must be a POD so we can fread/fwrite quickly
//
// WHY DO WE NEED THIS CLASS?
//
// We want to write a large number of small PODs to disk and read them back without
// 1. spurious calls to default constructors by std::vector
// 2. writing to disk a gazillion times
//
// SOLUTION
// A hybrid class containing a std::vector<> for adding new items and a
// std::unique_ptr<T[]> for fast persistence. From the user's POV, it looks
// like a std::vector<>.
//
// Algorithm
// 1. add new items into:
// std::vector<T> m_v;
// 2. when writing to disk, write out m_v as a chunk
// 3. when reading from disk, read into m_chunk (m_v will start empty again)
// 4. m_chunk and m_v combined will represent all the data
/*}}}*/
template<typename T>
class vector_chunk
{
// STATE /*{{{*/
size_t m_n_in_chunk;
std::unique_ptr<T[]> m_chunk;
std::vector<T> m_v;
/*}}}*/
// CONSTRUCTOR, INITIALIZATION /*{{{*/
public:
vector_chunk() : m_n_in_chunk( 0 ) { }
/*}}}*/
// EQUALITY /*{{{*/
public:
bool operator==( vector_chunk const& rhs ) const
{
if ( rhs.size()!=size() )
return false;
for( size_t i=0; i<size(); ++i )
if ( operator[]( i )!=rhs[i] )
return false;
return true;
}
/*}}}*/
// OSTREAM /*{{{*/
public:
friend std::ostream& operator<<( std::ostream& os, vector_chunk const& rhs )
{
for( size_t i=0; i<rhs.m_n_in_chunk; ++i )
os << rhs.m_chunk[i] << "\n";
for( T const& t : rhs.m_v )
os << rhs.t << "\n";
}
/*}}}*/
// BINARY I/O /*{{{*/
public:
void write_as_binary( std::ostream& os ) const
{
// write everything out
size_t const n_total = size();
os.write( reinterpret_cast<const char*>( &n_total ), sizeof( n_total ));
os.write( reinterpret_cast<const char*>( &m_chunk[0] ), m_n_in_chunk * sizeof( T ));
os.write( reinterpret_cast<const char*>( m_v.data() ), m_v.size() * sizeof( T ));
}
void read_as_binary( std::istream& is )
{
// only read into m_chunk, clear m_v
is.read( reinterpret_cast<char*>( &m_n_in_chunk ), sizeof( m_n_in_chunk ));
m_chunk.reset( new T[ m_n_in_chunk ] );
is.read( reinterpret_cast<char*>( &m_chunk[0] ), m_n_in_chunk * sizeof( T ));
m_v.clear();
}
/*}}}*/
// DELEGATION to std::vector<T> /*{{{*/
public:
size_t size() const { return m_n_in_chunk + m_v.size(); }
void push_back( T const& value ) { m_v.push_back( value ); }
void push_back( T&& value ) { m_v.push_back( value ); }
template< class... Args >
void emplace_back( Args&&... args ) { m_v.emplace_back( args... ); }
typename std::vector<T>::const_reference
operator[]( size_t pos ) const
{ return ((pos < m_n_in_chunk) ? m_chunk[ pos ] : m_v[ pos - m_n_in_chunk]); }
typename std::vector<T>::reference
operator[]( size_t pos )
{ return ((pos < m_n_in_chunk) ? m_chunk[ pos ] : m_v[ pos - m_n_in_chunk]); }
/*}}}*/
};
int main()
{
size_t const n = 10;
vector_chunk<Foo> v, w;
for( int i=0; i<n; ++i )
v.emplace_back( Foo{ i } );
std::filebuf ofb, ifb;
std::unique_ptr<std::ostream> osp;
std::unique_ptr<std::istream> isp;
ofb.open( "/tmp/junk.bin", (std::ios::out | std::ios::binary));
osp.reset( new std::ostream( &ofb ));
v.write_as_binary( *osp );
ofb.close();
ifb.open( "/tmp/junk.bin", (std::ios::in | std::ios::binary));
isp.reset( new std::istream( &ifb ));
w.read_as_binary( *isp );
ifb.close();
assert( v==w );
}
最佳答案
使用 vector::reserve()
然后写入 vector::data()
是一个肮脏的黑客和未定义的行为。请不要那样做。
解决这个问题的方法是使用自定义分配器,比如in this answer。 .我刚刚测试过它,在 clang 3.5 主干上工作正常,但不能用 gcc 4.7.2 编译。
虽然,正如其他人已经指出的那样,unique_ptr<T[]>
将很好地满足您的需求。
关于c++ - 如何创建一个可以二进制读/写大块的 std::vector-like 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21800655/
我需要(我必须)将大量 float 写入 qdatastream 并且我只使用 4 个字节是必要的。setFloatingPointPrecision 或为 float 和 double 写入 4 或
我有一些 C 代码,我用 Python 对其进行了扩展。扩展的 C 代码有一个将一些结构附加到二进制文件的函数: void writefunction(const struct struct1* so
我正在用 C 语言开发一个小软件,用于在布告栏中读取和写入消息。每条消息都是一个以渐进数字命名的 .txt。 软件是多线程的,有很多用户可以并发操作。 用户可以进行的操作有: 阅读整个公告板(所有 .
我有 2 个线程同时访问同一个大文件 (.txt)。 第一个线程正在从文件中读取。第二个线程正在写入文件。 两个线程都访问同一个 block ,例如(开始:0, block 大小:10),但具有不同的
我做了很多谷歌搜索,但我仍然不确定如何继续。 Linux 下最常见的剪贴板读写方式是什么?我想要同时支持 Gnome 和 KDE 桌面。 更新:我是否认为没有简单的解决方案,必须将多个来源(gnome
1. 定义配置文件信息 有时候我们为了统一管理会把一些变量放到 yml 配置文件中 例如 图片 用 @ConfigurationProperties 代替 @Value 使用方法 定义对应字段的实体
在开始之前,我必须先声明我是 FORTRAN 的新手。我正在维护 1978 年的一段遗留代码。它的目的是从文件中读取一些数据值,处理这些值,然后将处理过的值输出到另一个文本文件。 给定以下 FORTR
我正在制作一个应用程序,我需要存储用户提供的一些信息。我尝试使用 .plist 文件来存储信息,我发现: NSString *filePath = @"/Users/Denis/Documents/X
在delphi类中声明属性时是否可能有不同类型的结果? 示例: 属性月份:字符串读取monthGet(字符串)写入monthSet(整数); 在示例中,我希望在属性(property)月份中,当我:读
我正在以二进制形式将文件加载到数组中,这似乎需要一段时间有没有更好更快更有效的方法来做到这一点。我正在使用类似的方法写回文件。 procedure openfile(fname:string); va
我想实现一个运行模拟的C#控制台应用程序。另外,我想给用户机会在控制台上按“+”或“-”来加速/减速模拟的速度。 有没有办法在编写控制台时读取控制台?我相信我可以为此使用多线程,但是我却不怎么做(我对
这是我的代码: use std::fs::File; use std::io::Write; fn main() { let f = File::create("").unwrap();
我有一个应用程序可以访问 csv 文本文件中的单词。由于它们通常不会更改,因此我将它们放置在 .jar 文件中,并使用 .getResourceAsStream 调用读取它们。我真的很喜欢这种方法,因
我使用kubeadm,docker 17.12.1-ce和法兰绒网络安装了Kubernetes 1.13.1集群 但是,我发现Kubernetes主服务器上有许多空文件,权限为666,该文件允许任何用
我的工作区中有一些 java 文件。现在我想编写一个java程序,它可以读取来自不同源的文本文件,一次一个,一行一行,并将这些行插入到工作区中各自的java文件中。 文本文件会告诉我将哪个文件插入到哪
用户A要求系统读取文件foo,同时用户B想要将他或她的数据保存到同一个文件中。在文件系统级别如何处理这种情况? 最佳答案 大多数文件系统(但不是全部)使用锁定来保护对同一文件的并发访问。锁可以是独占的
我对保护移动应用程序的 firebase 数据库有一些疑问。 例如,在反编译Android应用程序后,黑客可以获取firebase api key 然后访问firebase数据库,这是正确的吗? 假设
我想让文件从外部不可删除,并希望使用java从程序对该文件进行读/写操作。 S0,我使用以下代码使用java创建了不可删除的文件: Process pcs = Runtime.getRunti
当 Selector.select() 以阻塞模式等待读/写操作时,是否可以将写消息推送到客户端?如何将选择器从阻塞模式移至写入模式?触发器可以是一个后台线程,用于放置需要写入给定 channel 的
我目前正在学习在 Linux 环境中使用 C 进行套接字编程。作为一个项目,我正在尝试编写一个基本的聊天服务器和客户端。 目的是让服务器为每个连接的客户端派生一个进程。 我遇到的问题是读取一个 chi
我是一名优秀的程序员,十分优秀!