#include <iostream>
#include <vector>
#include <exception>
//pass vectors by reference so the changes are reflected in the passed arguments
void Swap(std::vector<std::vector<int>> &A, std::vector<std::vector<int>> &B) {
int max_A = A.at(0).at(0); //if indexing A[0][0], exception would not be thrown
int max_B = B.at(0).at(0);
int index_Ai, index_Aj, index_Bi, index_Bj;
for (size_t i = 0; i < A.size(); i++) {
for (size_t j = 0; j < A.at(0).size(); j++) {
if (max_A < A[i][j]) { //indexing A[i][j] safe, cycle limited to vector size
max_A = A[i][j];
index_Ai = i;
index_Aj = j;
}
}
}
for (size_t i = 0; i < B.size(); i++) {
for (size_t j = 0; j < B.at(0).size(); j++) {
if (max_B < B[i][j]) {
max_B = B[i][j];
index_Bi = i;
index_Bj = j;
}
}
}
//standard library swap function
std::swap(A.at(index_Ai).at(index_Aj), B.at(index_Bi).at(index_Bj));
}
int main() {
std::vector<std::vector<int>> A = {{1, 2, 300}, {4, 9, 10, 56, 5, 6}};
std::vector<std::vector<int>> B = {{10, 45, 2, 12, 20, 80}, {40, 45, 500, 60}};
try{
Swap(A, B);
} catch(std::exception& e){ //if vectors accessed out of bounds throws exception
std::cout << "ERROR: " << e.what() << std::endl; //we catch it here
return EXIT_FAILURE;
}
for (auto &v : A) { //test print A
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
for (auto &v : B) { //test print B
for (auto i : v)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
return EXIT_SUCCESS;
}