简体   繁体   中英

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.

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. Then copying the deque to the vector using 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.

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. However, you can simply call std::reverse :

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

So, using only a vector :

  • You're allocating a single data structure instead of two; moreover, using reserve there will be a single memory allocation.

  • The use of reverse at the end simply replaces the use of copy you would have to do from the deque to the vector.

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).

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.

But why not try both and profile the code to see which one performs better?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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