在下面的代码中,每10个整数的许多向量构造有60%的几率,或者现有的向量被删除,有40%的几率.因此,会有很多调用new/malloc和delete.由于所有这些载体类型vector<int>,可以在这里自定义分配器的帮助,以减少电话new和delete,从而提高性能?这个想法是删除的矢量的空间可以由新构造的空间重用.这样的分配器怎么样?
注意:这个问题是关于分配器,它减少了对new和的调用delete.
#include <iostream>
#include <vector>
#include <random>
using namespace std;
int main()
{
// Random generator and distribution
mt19937 gen(123456);
uniform_real_distribution<> dis01(0., 1.);
// Make or delete 10E6 vectors.
vector< vector<int> > v; //the inner vectors will make many calls to new and delete
v.reserve(10E5); //assume some size.
for(int i=0; i<10E6; ++i)
{
if(dis01(gen)<0.6) // if true: make new sub-vector
{
v.emplace_back(); //new sub-vector
v.back().reserve(10);
for(int k=0; k<10; ++k) …Run Code Online (Sandbox Code Playgroud) 如何在不使用循环(如下所示)的情况下[91, 55, 77, 91]计算具有特定值(例如91)的向量(例如)中的元素?
fn count_eq(vec: &Vec<i64>, num: i64) -> i64 {
let mut counter = 0;
for i in vec {
if *i == num {
counter += 1;
}
}
return counter;
}
fn main() {
let v = vec![91, 55, 77, 91];
println!("count 91: {}", count_eq(&v, 91));
}
Run Code Online (Sandbox Code Playgroud) 尝试编译代码时出现此错误:
non-static reference member ‘Timestep& Timestep::previousTimestep’, can’t use default assignment operator
我创建Problem了Timestep一个引用,该引用Timestep应存储在vector中solution。此外,我想存储对先前的引用Timestep-对于第一个Timestep,这将是对自身的引用...
我读到,如果我const在类中尝试设置相等的成员,则需要定义自己的运算符。但是,const从代码中删除了所有元素,它仍然不起作用。有什么建议么?非常感谢。
class Problem {
public:
void initialTimestep(arma::vec ic);
private:
std::vector<Timestep> solution;
};
void Problem::initialTimestep(vec ic){
Timestep myFirstTimestep(starttime, ic, nodes);
solution.push_back(myFirstTimestep);
}
class Timestep {
public:
Timestep(double starttime, arma::vec initialCondition, arma::vec nodelist);
private:
Timestep& previousTimestep; //const
};
Timestep::Timestep(double starttime, vec initialCondition, vec nodelist)
: previousTimestep(*this)
{
//do stuff
}
int main() {
int k = …Run Code Online (Sandbox Code Playgroud) 我用 C++ 编写了一个模拟程序,并且喜欢使用 DEoptim 在 R 中查找参数。有时一切都运行良好,有时 DEoptim 会停下来并告诉我们:
Error in DEoptim(simulate, lower = lb, upper = ub, control = opt) :
NaN value of objective function!
Perhaps adjust the bounds.
Run Code Online (Sandbox Code Playgroud)
我的 R 脚本定义了一个调用外部二进制文件的函数。参数附加到命令中。我测试了我的 C++ 程序,但从未见过 NaN 返回。此外,为了进行调查,我检查 R 函数中是否存在 NaN simulate(),这样它就会停止并告知实际上存在一个 NaN 值。然而,它永远不会停在那里 - 但后来在 DEoptim 中。问题是什么?这是一个 DEoptim-Bug 吗?
library("DEoptim")
setwd("some-path")
simulate <- function(theta)
{
strcom <- paste(c("./ExternalBinary", theta),collapse=" ")
ret <- as.numeric(system(strcom, intern=T)) #will return a couple of integer numbers
ret <- mean(ret) #average those numbers
if(any(is.nan(ret))){ …Run Code Online (Sandbox Code Playgroud) 我基本上问了与在这里问过的问题相同的问题。然而,这个问题还没有得到回答。
我想在我的项目中使用 googletest。为此,我使用 ExternalProject_Add(),它使用 git 克隆测试套件。之后,我喜欢使用add_subdirectory().
这也是官方存储库中描述的内容。这种方法的好处是,googletest 中的构建脚本自己处理构建过程。
然而,问题是add_subdirectory()找不到源文件夹,因为它从一开始就不存在。因此,add_subdirectory()应视完成情况而定ExternalProject_Add()。
是否可以像 add_dependencies() 那样add_subdirectory()依赖ExternalProject_Add()于目标?
附注。如果我注释掉add_subdirectory(),构建它(由于缺少 googletest 库而以错误结束),取消注释并再次构建它(成功),我可以使其全部编译。
ExternalProject_Add(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
ExternalProject_Get_Property(googletest source_dir binary_dir)
set(GTEST_INCLUDE_DIR ${source_dir}/googletest/include)
set(GMOCK_INCLUDE_DIR ${source_dir}/googlemock/include)
add_subdirectory(${source_dir}
${binary_dir})
Run Code Online (Sandbox Code Playgroud) 我在这里看到了下面的代码。描述说:
我们还可以使用 auto&& 捕获作为转发参考。也就是说,对于左值引用,auto&& 将解析为 auto&;对于右值引用,auto&& 将解析为 auto&&。以下是在临时地图上捕获基于范围的 for 循环的输出的示例。
auto&&如果引用的值是左值,我确实理解 to 的auto&衰减(因此在这种情况下没有衰减)。我所努力的是理解临时地图、基于范围的 for 循环和移动的值如何一起工作。您愿意解释一下这些东西如何相互作用,以及为什么可以从正在迭代的临时对象中移动。
#include <iostream>
#include <map>
std::map<std::string, int> get_map()
{
return {
{ "hello", 1 },
{ "world", 2 },
{ "it's", 3 },
{ "me", 4 },
};
}
int main() {
for (auto&& [ k, v ] : get_map())
std::cout << "k=" << k << " v=" << v << '\n';
}
Run Code Online (Sandbox Code Playgroud) 我在某个类中注入依赖项。此类存储与 an 的依赖关系std::unique_ptr,因此是该对象的唯一所有者。
在这种依赖关系中模拟方法的正确方法是什么?unique_ptr我当前的解决方案是在移交所有权之前获取原始指针。虽然这有效,但我认为还有更好的方法可以做到这一点。这些是什么?
class Dependency
{
public:
virtual int plusOne(int x) {return x+1;}
};
class Dependency_Mock : public Dependency
{
public:
MOCK_METHOD1(plusOne, int(int));
};
class SomeClass
{
public:
void inject(std::unique_ptr<Dependency> dep) {dependency = std::move(dep);}
int execute(int x) {return dependency->plusOne(x);}
private:
std::unique_ptr<Dependency> dependency;
};
TEST(SomeClassTest, executeTestWithMock)
{
SomeClass some;
auto dep = std::make_unique<Dependency_Mock>();
auto& dep_ref = *(dep.get()); // This is kind of ugly.
some.inject(std::move(dep));
EXPECT_CALL( dep_ref , plusOne(_))
.WillOnce(Return(5));
EXPECT_EQ(some.execute(5), 5); // execute
}
Run Code Online (Sandbox Code Playgroud) 我想检查一个类型T也是参数包的一部分Ts.有些解决方案可以在C++ 14中实现,但如果在C++中可以简化这一点,我就会徘徊17.如果T在Ts编译器中找不到应该停止(static_assertion应该失败).
template<typename... Ts>
class A
{
template<typename T>
void action() {
// check that T is also in Ts (static_assertion)
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个唯一(!)元素的向量,并希望删除一个具有特定值的元素.这个元素很可能接近向量的末尾.因此,我想从头开始寻找这个元素.
我认为这应该有效,但事实并非如此.
vec.erase( find(crbegin(vec), crend(vec), value) ); //does not work
Run Code Online (Sandbox Code Playgroud)
编译器sais(缩短):
error: no matching function for call to 'std::vector<unsigned int>::erase(std::reverse_iterator<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int> > >)'
and also
note: no known conversion for argument 1 from 'std::reverse_iterator<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int> > >' to 'std::vector<unsigned int>::const_iterator {aka __gnu_cxx::__normal_iterator<const unsigned int*, std::vector<unsigned int> >}'
Run Code Online (Sandbox Code Playgroud)
如果我不使用反向迭代器,它可以工作(因此编译器注释):
vec.erase( find(cbegin(vec), cend(vec), value) ); //works
Run Code Online (Sandbox Code Playgroud)
如何判断它应该从头开始搜索value?
编辑:我知道,该向量包含搜索到的元素.
我有一个在可变参数模板类中给出的参数包,并希望提取第一个类型.
目前我这样做,工作正常,但有点麻烦.有可能做同样的事情更简单吗?FirstEntityType应定义为具有第一种类型的类型EntityTs.注意,我想保留类模板的签名.我知道写作是可能的template<typename FirstEntityType, typename... OtherEntityTypes>,但这是我不想做的事情.
template<typename... EntityTs>
class EntityContext
{
template<typename T, typename ... Ts>
struct K {
using type = T;
};
using FirstEntityType = typename K<EntityTs...>::type;
// ...
}
Run Code Online (Sandbox Code Playgroud) c++ ×8
c++17 ×4
googletest ×2
vector ×2
allocator ×1
cmake ×1
const ×1
googlemock ×1
iterator ×1
optimization ×1
parameters ×1
performance ×1
r ×1
rust ×1