我想使用boost来(de)压缩gzip流(不是文件),所以我写了这段代码:
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <sstream>
int main(int argc, char** argv) {
std::stringstream ss, comp, decomp;
ss << "Hello World";
boost::iostreams::filtering_streambuf< boost::iostreams::input> in;
in.push(boost::iostreams::gzip_compressor());
in.push(ss);
boost::iostreams::copy(in, comp);
std::cout << "Compressed: ";
std::cout << comp.str() << std::endl;
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::gzip_decompressor());
inbuf.push(comp);
boost::iostreams::copy(inbuf, decomp);
std::cout << "Decompressed: ";
std::cout << decomp.str() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
它的目的是首先压缩一个字符串,然后将其解压缩为原始字符串.这段代码编译得很好但是当我执行它时,压缩部分工作并打印其输出但是对于解压缩部分,我得到这个错误:
terminate called after throwing an instance of'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::gzip_error> >'
what(): gzip error
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)
那么请你告诉我我做错了什么?
UPDATE
如果我将压缩器和解压缩器更改为bz2格式(使用bzip2_compressor和bzip2_decompressor方法),错误将消失,它将正常工作.
我正在优化一个c ++代码,在这个代码中我遇到了一个可以简化如下的情况.
考虑以下代码:
#include <iostream>
#include <thread>
using namespace std;
bool hit = false;
void F()
{
this_thread::sleep_for(chrono::seconds(1));
hit = true;
}
int main()
{
thread t(F);
while (!hit)
;
cout << "finished" << endl;
t.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这基本上启动一个线程,在一秒之后将更改hitto 的值true.同时代码进入一个空循环,这个循环将一直持续到hit值为止true.我gcc-5.4使用-g旗帜编译了这一切,一切都很好.代码将输出finished并结束.但后来我用-O2flag 编译它,这次代码无限地卡在循环中.
查看反汇编,编译器生成了以下内容,这是无限循环的根本原因:
jmp 0x6ba6f3!0x00000000006ba6f3
好吧,很明显,编译器已经推断出它hit的值是false并且它不会在循环中改变所以为什么不假设它是一个无限循环而不考虑另一个线程可能改变它的值!并且此优化模式添加在更高级别(-O2)中.由于我不是一个优化标志专家,任何人都可以告诉我其中哪一个对此结果负责,所以我可以将其关闭?关闭它会对其他代码有任何重大的性能成本吗?我的意思是,这种代码模式有多少是罕见的?
我想要的是一种复制std::vector<int>到另一个std::vector<myStruct>与赋值操作符,其中myStruct可分配的int.所以我写了这段代码:
#include <vector>
#include <iostream>
using namespace std;
struct myStruct
{
myStruct(int& a) : _val(a) { }
myStruct(int&& a) : _val(a) { }
myStruct& operator=(int& a)
{
_val = a;
return *this;
}
int _val;
};
int main()
{
vector<int> ivec;
ivec.push_back(1);
vector<myStruct> svec = ivec;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给了我错误,因为它找不到有效的转换std::vector<myStruct>,std::vector<int>虽然int可以隐式转换为myStruct.另一方面,不能在类外声明赋值运算符,因此我推断手动编写运算符不是一种选择.那么在这种情况下我该怎么办?
***更新:正如Blastfurnace和其他人所说,这可以使用此代码而不是赋值来解决:
vector<myStruct> svec(ivec.begin(), ivec.end());
Run Code Online (Sandbox Code Playgroud)
但是想象一下,在我想要写一个库,并要处理这个库本身,使用户可以只写情况std::vector<myStruct> svec = someFunction()中someFunction返回 …
我想在matlab中做一些统计计算,所以我的数字非常小(介于0和1之间),大量的乘法使它们更小我使用双重类型进行工作但是我注意到它只存储了我的数字的5位数对于较大的数字,它存储10的幂.所以它肯定会导致最终答案中的一个非常大的错误.如何使用更准确的数字类型?谢谢您的帮助
c++ ×3
boost ×1
compression ×1
gcc ×1
gzip ×1
matlab ×1
optimization ×1
precision ×1
stl ×1
template-argument-deduction ×1
vector ×1