"Second Attack"
-
Please help me find a mistake in the algorithm, like everything works right, but sometimes there's a mistake with different input data. So I've decided to implement the algorithm of the second attempt. Shortly about the task, there's a memory of a limited size, and the pages, the algorithm of FIFO, unlike if the page is in memory, it's translated at the end of the queue. I've got a page that's in memory and removed from her position, and the page is added at the end of the line (if they match).
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <deque> #include <algorithm> #include <utility> #include <cstdlib>
void show_fifo(const deque<int> &dq)
{
deque<int>::const_iterator i;
for (i=dq.begin(); i != dq.end(); ++i)
{
cout << *i << " ";
}
cout << endl;
}
int main()
{
int mem_size = 5;
int access_num;
access_num = 13;
int array[] = { 1, 2, 3, 4, 5, 2, 3, 4, 1, 5, 4, 1, 3};cout << "Vtoraya popbitka: " << endl; // Vtoraya popitka deque<int> dq; for (int i=0; i<mem_size; i++) { dq.push_back(-1); } cout << "Memory: " << endl; show_fifo(dq); for (int i = 0; i < access_num; ++i) { cout << "Step " << (i+1) << ":" << endl; for (int j = 0; j < dq.size(); j++) { if ((find(dq.begin(), dq.end(), array[i]) != dq.end()) && (dq.size() != 0)) { cout << "Page: " << array[i] << " has in memory" << endl; int del = dq.at(array[i]); dq.erase(dq.begin()+del); dq.push_front(array[i]); break; } else { dq.push_front(array[i]); dq.pop_back(); break; } } show_fifo(dq); }
-
If I understand the code correctly, you're checking whether there is.
array[i]
Totaldq
and if there is, "replace him at the end of the line, by removing and putting him to the end. If that's what you're saying:for (int j = 0; j < dq.size(); j++) { deque<int>::iterator ii = find(dq.begin(), dq.end(), array[i]);
if ( ii != dq.end() ) { cout << "Page: " << array[i] << " has in memory" << endl; dq.erase(ii); dq.push_front(array[i]); break; } else { dq.push_front(array[i]); dq.pop_back(); break; } }
You already have a terator to indicate where to remove why to reshape from.
int del = dq.at(array[i]);
dq.erase(dq.begin()+del);
?
(I understand this place is falling)By the way, placing at the end of the queue through removal/supply is not optimal, it's easier to do.
deque<int>::iterator ii = find(dq.begin(), dq.end(), array[i]);
if ( ii != dq.end() ) { cout << "Page: " << array[i] << " has in memory" << endl; deque<int>::reverse_iterator temp = dq.rbegin(); // получить итератор на последний элемент std::swap(*ii, *temp); // обменять значения итераторов break; }