gpt4 book ai didi

c++ - 在 C++11 中为嵌套循环返回 vector 的最佳实践

转载 作者:行者123 更新时间:2023-11-30 01:52:11 27 4
gpt4 key购买 nike

我想从类成员函数返回一个指向 vector 的指针 vector 。该函数将从嵌套循环中调用,请求 vector (并处理它的元素)数百万次,因此应避免不必要的(重新)分配。

Bjarne Stroustrup recommends returning collections by value ,由于 C++11 移动语义。然而,在我看来,第二种方法 (doStuff2) 对我来说更好,因为它支持 vector 重用。有什么建议吗?

template <typename T>
class A
{
typedef std::vector<T> TVec;
std::vector<TVec> m_items;

public:

size_t getIndex(size_t i, size_t j);

std::vector<TVec*> doStuff(float x, float y)
{
// calculate n, i0, i1, j0, j1 (by x and y)
// ...

std::vector<TVec*> vec;
vec.reserve(n);

for (size_t i = i0; i<i1; i++)
for (size_t j = j0; j<j1; j++)
vec.push_back(&m_items[getIndex(i, j)]);

return vec;
}

void doStuff2(float x, float y, std::vector<TVec*> &vec)
{
// calculate n, i0, i1, j0, j1 (by x and y)
// ...

vec.clear();
vec.reserve(n);

for (size_t i = i0; i<i1; i++)
for (size_t j = j0; j<j1; j++)
vec.push_back(&m_items[getIndex(i, j)]);
}
};

最佳答案

However it seems to me that the second approach (doStuff2) is better in my case, since it supports vector reuse. Any suggestions?

第二个选项 (doStuff2) 比第一个好,因为它避免了重新分配 vector 。也就是说,您应该(可能)考虑使用访问者模式:

您的代码(如果我理解正确的话):

// "function will be called from a nested loop, requesting the vector
// (and processing it's elements) million times, so unnecessary
// (re)allocations should be avoided."
void yourCientCode()
{
std::vector<TVec*> vec;
for(auto x: ???) for(auto y: ???) // nested loop (a million(?) times)
{
A::doStuff2(x, y, vec);
performClientComputation(vec);
}
}

替代代码:

// "function will be called from a nested loop, requesting the vector
// (and processing it's elements) million times, so unnecessary
// (re)allocations should be avoided."
void yourCientCode()
{
for(auto x: ???) for(auto y: ???) // nested loop
{
A::doStuff3(x, y, performClientComputation); // computation function should
// be injected as a visitor
}
}

这样,不会返回 vector 。客户端代码不必“获取 vector 然后应用计算”,而是“对满足任何条件的元素应用计算”(参见得墨忒尔定律)。

拥有(或不拥有) vector 成为内部实现细节(就客户端代码而言)并且可以在以后进行优化,而根本不改变客户端代码。

关于c++ - 在 C++11 中为嵌套循环返回 vector 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033368/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com