Domanda

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?

È stato utile?

Soluzione

You may use a std::deque() and its pop_front() method.

Altri suggerimenti

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];
}

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 (i.e. access by any explicit index) in O(1) (i.e. constant access time, i.e. very fast).

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

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top