Другие языки программирования и технологии

С++ Как создать массив кортежей и записать значения

Кортежи должны иметь вид tuple<*char, int, int, int>
Помогите создать массив кортежей и записать значения для примера в них.
#include < iostream >
#include < tuple >
#include < string >
#include < windows.h >

using namespace std;

void main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
system("color 0A");
cout << "Введите число элементов в массиве ";
unsigned n;
cin >> n;
auto arr = new tuple < string, int, int, int > [n];
for (unsigned u = 0; u < n; ++u)
{
string s;
int a, b, c;
cout << "Элемент " << u + 1 << endl;
cout << "Введите строку ";
cin.ignore(cin.rdbuf()->in_avail(), '\n');
getline(cin, s);
cout << "Введите 3 числа через пробелы ";
cin >> a >> b >> c;
arr[u] = make_tuple(s, a, b, c);
}
for (unsigned u = 0; u < n; ++u)
{
cout << get<0>(arr[u]) << " " << get<1>(arr[u]) << " " << get<2>(arr[u]) << " " << get<3>(arr[u]) << endl;
}
cin.get(); cin.get();
}

Вот код на STL - контейнер.

#include < iostream >
#include < tuple >
#include < string >
#include < windows.h >
#include < vector >
#include < algorithm >

using namespace std;

void main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
system("color 0A");
cout << "Введите число элементов в массиве ";
unsigned n;
cin >> n;
vector < tuple < string, int, int, int > > v(n);
unsigned u = 0;
auto gen = [u]() mutable -> tuple < string, int, int, int >
{
string s;
int a, b, c;
cout << "Элемент " << ++u << endl;
cout << "Введите строку ";
cin.ignore(cin.rdbuf()->in_avail(), '\n');
getline(cin, s);
cout << "Введите 3 числа через пробелы ";
cin >> a >> b >> c;
return make_tuple(s, a, b, c);
};
generate(v.begin(), v.end(), gen);

for (auto t : v)
{
cout << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << " " << get<3>(t) << endl;
}
cin.get(); cin.get();
}
Раис Сулейманов
Раис Сулейманов
8 552
Лучший ответ
Если уже решили использовать std::tuple, то логичнее использовать вместо массива std::vector, а вместо указателя на char – std::string

#include <iostream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
using user_t = tuple<string, int, int, int>;
user_t input() {
cout << "String: ";
string s;
getline(cin, s);
int i[3];
for (size_t n = 0; n < 3; ++n) {
cout << n + 1 << " integer: ";
cin >> i[n];
}
cin.ignore(numeric_limits<int>::max(), '\n');
cout.put('\n');
user_t ut(s, i[0], i[1], i[2]);
return ut;
}
void output(const user_t& ut) {
cout
<< get<0>(ut) << ": "
<< get<1>(ut) << "; "
<< get<2>(ut) << "; "
<< get<3>(ut) << '\n';
}
int main() {
vector<user_t> box;
for (size_t i = 0; i < 5; ++i) box.emplace_back(input());
system("cls");
for (const auto &item : box) output(item);
system("pause");
}