Quantcast
Channel: C++ Queue Implementation - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 4

Answer by coderodde for C++ Queue Implementation

$
0
0

I have only a couple of minor comments:

1

void push(T element) {    if (m_endIndex == m_startIndex && m_size > 0) {        // expand queue        expand_queue();    }    m_buffer[m_endIndex] = element;    m_endIndex = (m_endIndex + 1) % m_capacity;    m_size++;}

Why not write simply if (m_size == m_capacity) ... ?

2

if (m_endIndex <= m_startIndex) {    int cnt = 0;    for (int i = m_startIndex; i < m_capacity; i++) {        newBuffer[cnt++] = m_buffer[i];    }    for (int i = 0; i < m_endIndex; i++) {        newBuffer[cnt++] = m_buffer[i];    }} else {    int cnt = 0;    for (int i = m_startIndex; i < m_endIndex; i++) {        newBuffer[cnt++] = m_buffer[i];    }            

}

The above could be written more succintly as

for (int i = m_startIndex, cnt = 0; cnt < m_size; ++i, ++cnt) {    newBuffer[cnt] = m_buffer[i % m_capacity];}

3

Finally, if you could guarantee that the internal storage array has capacity that is always a power of two, you could substitute:

index % m_capacity --> index & m_mask, 

where m_mask == m_capacity - 1.

Hope that helps.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>