1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
#include <map>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using Data = int;
using Values = std::vector<Data>;
using DB = std::map <std::string, Values>;
template<typename T = Data>
[[nodiscard]]
T getNum(const std::string& txt) {
for (std::string input; ; ) {
if (T response {}; (std::cout << txt) && (std::getline(std::cin, input)))
if (std::istringstream is { input }; (is >> response) && !(is >> input))
return response;
std::cin.clear();
std::cerr << "Not a number!\n";
}
}
template<typename T = Data>
[[nodiscard]]
T getNum(const std::string& txt, T mn, T mx) {
T val {};
do val = getNum(txt);
while ((val < mn || val > mx) && (std::cout << "Number out of range\n"));
return val;
}
[[nodiscard]]
auto menu() {
std::cout << "\n1. Create a new vector of integers\n";
std::cout << "2. Add a new integer to a vector\n";
std::cout << "3. Delete a vector\n";
std::cout << "4. Display a vector\n";
std::cout << "0. Exit\n\n";
return getNum("Enter a menu option number: ", 0, 4);
}
[[nodiscard]]
auto getName() {
std::string name;
std::cout << "Enter name of integer vector: ";
std::getline(std::cin, name);
return name;
}
[[nodiscard]]
auto findVec(const std::string& nam, DB& db) {
return db.find(nam);
}
bool newVect(DB& db) {
return db.emplace(getName(), Values {}).second;
}
bool addInt(DB& db) {
if (const auto dbit { findVec(getName(), db) }; dbit != db.end()) {
dbit->second.emplace_back(getNum("Enter integer value: "));
return true;
}
return false;
}
bool delVect(DB& db) {
if (const auto dbit { findVec(getName(), db) }; dbit != db.end()) {
db.erase(dbit);
return true;
}
return false;
}
bool disVect(DB& db) {
if (const auto dbit { findVec(getName(), db) }; dbit != db.end()) {
for (const auto& d : dbit->second)
std::cout << d << ' ';
std::cout << "\n\n";
return true;
}
return false;
}
int main() {
DB data;
for (int opt { 1 }; opt; ) {
switch (opt = menu(); opt) {
case 1:
if (!newVect(data))
std::cout << "Could not create new vector\n";
break;
case 2:
if (!addInt(data))
std::cout << "Could not add integer\n";
break;
case 3:
if (!delVect(data))
std::cout << "Could not erase vector\n";
break;
case 4:
if (!disVect(data))
std::cout << "Could not display vector\n";
break;
}
}
}
|