【发布时间】:2020-04-02 11:16:19
【问题描述】:
我是编程初学者。我有一个问题。我正在尝试对 Enigma 机器进行编码。我有两节课。一个用于 Enigma,一个用于转子。转子是谜机的小部件,这对问题无关紧要。我的问题是错误。我无法计算,函数cout << rotors[0].GetRotor(); 应该返回我的整数向量。我不知道为什么会这样。我的程序不需要它,但我不确定我将转子添加到 enigma void AddRotor(Rotor rotor) { rotors.push_back(rotor); }function(在“TakeRotors”函数中调用)是否正常工作。在我看来,它应该工作得很好,但我无法检查它。不幸的是,调试器没有显示vector<Rotor> rotors; 排列的任何值,所以我不确定:( 任何帮助都会很棒。谢谢。
这是我完整的、需要的代码:)
#include <iostream>
#include <vector>
using namespace std;
class Rotor {
public:
vector <int> permutation;
int position;
Rotor(vector<int> permutation) {
position = 0;
permutation;
}
vector<int> GetRotor() const {
return permutation;
}
};
class Enigma {
public:
vector<Rotor> rotors;
void AddRotor(Rotor rotor) {
rotors.push_back(rotor);
}
void PrintRotor(const vector<Rotor>& rotors) {
cout << rotors[0].GetRotor(); // Error right here
cout << rotors[0].position;
}
void setupRotor(int index) {
Rotor rotor = rotors[index];
}
void MoveRotor(int index) {
rotors[index].position++;
cout << "Before" << endl;
// cout << rotors[index].permutation.data << ' ';
Enigma::PrintRotor(rotors);
rotate(rotors[index].permutation.begin(), rotors[index].permutation.begin() + rotors[index].permutation.size(), rotors[index].permutation.end());
cout << "After" << endl;
Enigma::PrintRotor(rotors);
}
};
vector<int> take_numbers(int number) {
vector<int> numbers;
for (int i = 0; i < number; i++) {
int number;
cin >> number;
numbers.push_back(number);
}
return numbers;
}
void take_rotors(int number_letters, Enigma* enigma) {
int numberOfRotors;
// int numberOfNotch, positionOfNotch;
cout << "Give number of Rotors" << endl;
cin >> numberOfRotors;
for (int i=0; i < numberOfRotors; i++) {
vector<int> permutation = take_numbers(number_letters);
Rotor Rotor(permutation);
enigma->AddRotor(Rotor); // I am not sure if it adds Rotors fine.
}
}
int main()
{
Enigma enigma;
int number_letters, move_rotor;
cout << "Give number of letters in alphabet" << endl;
cin >> number_letters;
take_rotors(number_letters, &enigma);
// take_reflectors(number_letters, &enigma);
cout << "Which rotor do you want to move (index)" << endl;
cin >> move_rotor;
enigma.MoveRotor(move_rotor);
return 0;
}
【问题讨论】:
-
如何将整数向量写入控制台?制表符分开?空间分隔?逗号分隔?每行一个?你得到这个错误是有原因的,那是因为 iostream 没有被编码为默认接受向量或任何其他复杂对象(你需要自己编写代码)。