简体   繁体   中英

c++ vector insertion and reading

I am inserting elements with push_back in a vector. I want to read the data in FIFO and using iterator assigned to begin of vector. Is there any other approach of reading data in FIFO in a vector?

您可以使用std::deque()及其pop_front()方法。

The code would be:

auto value = myvector[0];
myvector.erase(myvector.begin());

However, removing elements from the beginning (or somewhere in between) is slow, because it must copy the whole array. Access is fast though: vector allows random access (ie access by any explicit index) in O(1) (ie constant access time, ie very fast).

But another container structure instead of vector might make more sense for you, eg list or deque . Some STL implementations (or other framework) also have something like rope which is in many cases the best of both worlds.

You can access the elements of a vecotr just like you would access the elements of an array:

std::vector<std::string> vec;
// Excluded: push items onto vec
for (int i = 0; i < vec.size(); ++i) {
  // Example:
  std::cout << vec[i];
}

There's nothing special to pay attention to. To insert, use push_back , to extract, you need something like:

if ( !fifo.empty() ) {
    ValueType results = fifo.front();
    fifo.erase( fifo.begin() );
}

(Don't forget to check for empty before trying to remove an element.)

An important point to remember is that both push_back and in some cases erase can invalidate iterators, so you don't want to keep iterators into the underlying vector hanging around.

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