#include <iostream>
#include <vector>
#include <unordered_map>
const int CACHE_SIZE = 16; // Number of cache lines
// CacheLine class
class CacheLine {
public:
int tag;
bool valid;
int data;
CacheLine() : tag(-1), valid(false), data(0) {}
};
// Cache class
class Cache {
public:
std::vector<CacheLine> lines;
Cache() : lines(CACHE_SIZE) {}
int read(int address) {
int index = address % CACHE_SIZE;
int tag = address / CACHE_SIZE;
if (lines[index].valid && lines[index].tag == tag) {
// Cache hit
std::cout << "Cache hit: Address " << address << " -> Data " << lines[index].data << std::endl;
return lines[index].data;
} else {
// Cache miss
std::cout << "Cache miss: Address " << address << std::endl;
return -1;
}
}
void write(int address, int data) {
int index = address % CACHE_SIZE;
int tag = address / CACHE_SIZE;
lines[index].tag = tag;
lines[index].valid = true;
lines[index].data = data;
std::cout << "Writing data " << data << " to address " << address << std::endl;
}
};
int main() {
Cache cache;
// Writing data to cache
cache.write(10, 100);
cache.write(26, 200); // This will replace data at address 10 due to direct-mapping
// Reading data from cache
cache.read(10); // This will be a cache miss
cache.read(26); // This will be a cache hit
return 0;
}