简体   繁体   English

C ++ Std队列和矢量性能

[英]C++ Std queue and vector performance

I've been working with graphs lately, and I am looking into returning a path from a graph. 我最近一直在处理图表,我正在寻找从图表中返回路径。 The path needs to be returned as a std vector containing all of the nodes with the starting node first. 该路径需要作为std向量返回,该向量包含首先具有起始节点的所有节点。

I've been looking at two options: - use the slow vector insert method to add the nodes at the front of the vector - use a deque to add the nodes to the front (push_front), which is much faster. 我一直在寻找两个选项: - 使用慢向量插入方法在向量的前面添加节点 - 使用deque将节点添加到前面(push_front),这要快得多。 Then copying the deque to the vector using std::copy 然后使用std :: copy将双端队列复制到向量

Is there a significant performance boost using one method over the other? 使用一种方法比另一种方法有显着的性能提升吗?

Since you're returning a path, you presumably have an upper bound on its length. 因为你正在返回一条路径,所以你的长度可能会有一个上限。 Therefore, you can call create a vector , call reserve and later (as @user2079303 writes) call push_back to add vertices to the path. 因此,您可以调用create a vector ,call reserve和稍后(如@ user2079303写入)调用push_back将顶点添加到路径中。

const auto n = <graph_size>
std::vector<size_t> path;
path.reserve(n)
...
v.push_back(i); // Push whatever you want.

Now the problem is that, at least from the question, it seems like v is in the reversed order. 现在的问题是,至少从问题来看,似乎v是颠倒的顺序。 However, you can simply call std::reverse : 但是,您只需调用std::reverse

std::reverse(std::begin(v), std::end(v));

So, using only a vector : 所以,只使用一个vector

  • You're allocating a single data structure instead of two; 您正在分配单个数据结构而不是两个; moreover, using reserve there will be a single memory allocation. 而且,使用reserve会有一个内存分配。

  • The use of reverse at the end simply replaces the use of copy you would have to do from the deque to the vector. 最后使用reverse只是替换了你需要从deque到vector的copy的使用。

If you are looking at wrapping a std::vector in a std::queue then the std::queue will push elements to the back of the vector (the fast way). 如果你正在寻找在std::queue中包装std::vector ,那么std::queue会将元素推送到向量的后面 (快速方式)。

Even if not however, because a std::vector is contiguous storage, it is possible it will out-perform a std::deque even if you push_font() because it plays well with the CPU cache where shuffling data is fast. 即使不是这样,因为std::vector是连续存储,即使你使用push_font() ,它也可能会超出std::deque因为它可以很好地与CPU缓存很好地混合数据。

But why not try both and profile the code to see which one performs better? 但是为什么不试试这两个并分析代码以查看哪个代码表现更好?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM