Как просмотреть содержимое вектора, в котором записана собственная структура?
У меня есть структура, которая записывается в вектор. Но хочется убедиться, что программа работает верно. Для этого хочу посмотреть содержимое вектора, но не совсем понимаю, как это сделать, подскажите пожалуйста
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <vector>
#include <set>
#include <map>
using namespace std;
struct Assembler_Command
{
int address;
int operand;
string command;
string strOperand;
};
vector<Assembler_Command> assembler;
set<string> variables;
int current_address = 0, current_num_row = 0;
bool end_programm = false;
void Add_Assembler_Command(string command, string strOperand, int operand = 0)
{
Assembler_Command assembler_cmd;
assembler_cmd.address = current_address++;
assembler_cmd.command = command;
assembler_cmd.strOperand = strOperand;
assembler_cmd.operand = operand;
assembler.push_back(assembler_cmd);
}
int Processing_Command(string command, string params)
{
if (command == "REM")
{
return 0;
}
else if (command == "INPUT")
{
if (params.size() == 1 && (params[0] >= 'A' && params[0] <= 'Z'))
{
variables.insert(params);
Add_Assembler_Command("READ", params);
return 0;
}
}
return 0;
}
int main()
{
string params = "A";
string command = "INPUT";
Processing_Command(command, params);
return 0;
}
Ответы (3 шт):
Вопрос в том, как организовать вывод содержимого вектора
Как-то так устроит?
for(const auto& e: assembler)
{
cout << "address: " << e.address << endl;
cout << "operand: " << e.operand << endl;
cout << "command: " << e.command << endl;
cout << "operand: " << e.strOperand << endl;
}
Есть более красивое и надежное решение. Нужно определить оператор operator<< для всех интересующих структур. И тогда все будет "магическим образом" работать. Для начала сделаем для структуры Assembler_Command
std::ostream& operator<<(std::ostream& os, const Assembler_Command& command) {
os << "{address:" << command.address << ", operand: " << command.operand << ", command: " << command.command << ", operand: " << command.operand << "}";
return os; // это обязательно в конце
}
выглядит страшненько, но считайте, что os - это просто std::cout и нужно передать ссылку на Ваш объект.
Все, теперь можно делать вот так
Assembler_Command cmd;
//...
std::cout << cmd;
более того, можно даже в файл выводить или в std::cerr.
Теперь вторая половина квеста - это вектор. Тут есть много идей, но суть та же. Я обычно копипащу готовый код, который выводит шаблонный вектор (и оно работает для любого вектора)
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec)
{
for (auto& el : vec)
{
os << el << ' ';
}
return os;
}
(взято тут https://coliru.stacked-crooked.com/)
все, теперь можно выводить в консоль любой вектор прям вот так
std::vector<int> x;
std::cout << x;
Правда лучше чуточку доделать вывод. Я люблю вот такой код
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec)
{
os << "[ ";
for (auto& el : vec)
{
os << el << ' ';
}
os << "]";
return os;
}
С минимальными переделками (заголовок функции) этот код может выводить и std::set (в котором хранятся какие то переменные)
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& st) { ... }
начиная со стандарта 17 можно так сделать
#include <iostream>
#include <vector>
#include <tuple>
struct Assembler_Command
{
int address;
int operand;
std::string command;
std::string strOperand;
};
int main()
{
std::vector<Assembler_Command> assembler {{1, 1, "Command 1","strOperand 1"}, {2, 2, "Command 2","strOperand 2"}}; //инициализировать можно теперь так
for (const auto&[address, operaand, command, strOperand]:assembler)///Теперь можно получить доступ к ее членам с помощью декомпозиции.
{
std::cout <<"\n ID \t"<<address
<<"\n Name \t"<<operaand
<<"\n Role \t"<<command
<<"\n Salary \t"<<strOperand <<std::endl;
}
assembler.at(0).address=4; //изменить отдельные поля
assembler.at(0).command="Broo";
for (const auto&[address, operaand, command, strOperand]:assembler)
{
std::cout <<"\n ID \t"<<address // можно выводить только то что нужно
<<"\n Role \t"<<command
<<std::endl;
}
}