我有一个函数,使用均匀分布填充具有min和max之间随机值的容器.
#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
template<typename TContainer>
void uniform_random(TContainer& container,
const typename TContainer::value_type min,
const typename TContainer::value_type max) {
std::random_device rd;
std::mt19937 gen(rd());
// Below line does not work with integers container
std::uniform_real_distribution<typename TContainer::value_type> distribution(min, max);
auto lambda_norm_dist = [&](){ return distribution(gen); };
std::generate(container.begin(), container.end(), lambda_norm_dist);
}
int main() {
std::vector<float> a(10);
uniform_random(a,0,10);
for (auto el : a) { std::cout << el << " "; }
}
Run Code Online (Sandbox Code Playgroud)
更换std::vector<float>
与std::vector<int>
不工作,因为我将不得不使用std::uniform_int_distribution
来代替.是否有一种简单而优雅的方法来根据value_type参数选择正确的构造函数?
我到目前为止尝试使用std::numeric_limits<typename …
我有一个模板化的基类Base
和一个模板化的派生类Derived
,我想序列化.
下面的简化代码编译并运行,但不从基类序列化数据成员.
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/export.hpp>
template<class U, class V>
struct Base {
Base(U uu, V vv) : u(uu), v(vv) {}
U u;
V v;
};
template<class V, class T>
struct Derived : public Base<V, int>, public Base<V, std::string> {
Derived(T tt) : Base<V, int>(2.0, 4), Base<V, std::string>(3.0, std::string("hello")), t(tt) {}
T t;
};
// does not work
//BOOST_CLASS_EXPORT(Derived);
namespace boost { …
Run Code Online (Sandbox Code Playgroud) 我正在寻找二维数组指针的重载 [] 运算符来访问单元格元素。
二维数组作为 传递给我的函数int *arr
。
我们可以通过*(arr+i*N+j)
其中N
is 列数、i
is 行索引和j
is 列索引来访问单元格元素。
但是我们可以使用一些宏或运算符重载来编写这样的代码arr[i,j]
,或者为了更好的可读性吗?arr(i,j)
有什么建议吗?
我想打印一个std :: unique_ptr,它是Bar的类成员.但是,以下代码不起作用请参阅我对流<< bar.foo_unique(); 我想我应该改变我的foo_unique()访问器,但我不知道怎么做.
#include <iostream>
#include <memory>
class Foo
{
public:
Foo() : n_(1) {}
int n() const { return n_; }
private:
int n_;
};
std::ostream& operator<< (std::ostream& stream, const Foo& foo);
std::ostream& operator<< (std::ostream& stream, const Foo& foo)
{
stream << foo.n();
return stream;
}
class Bar
{
public:
Bar() : m_(2), foo_(), foo_unique_(std::make_unique<Foo>()) {}
int m() const { return m_; }
const Foo& foo() const { return foo_; }
const std::unique_ptr<Foo>& foo_unique() const { …
Run Code Online (Sandbox Code Playgroud)