我是程序初学者,我有个问题。我在试图对Enigma机器进行编码。我有两堂课。一个给Enigma,一个给转子。转子是神秘机器的小部件,这与问题无关。我的问题是错误。函数cout << rotors[0].GetRotor();应该返回我的整数向量。我不知道这是为什么。我不需要在我的程序,但我不确定我的添加转子的谜void AddRotor(Rotor rotor) { rotors.push_back(rotor); }函数,在"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;
}发布于 2020-04-02 11:23:11
没有operator<<(std::ostream&,const std::vector<int>&),如果你想要它,你需要自己提供。但是,不建议为您不拥有的类型重载运算符,因此我宁愿编写一个函数:
void print_vector(std::ostream& out, const std::vector<int>& vect) {
for (int i : vect) {
out << i << '\n';
}
}你可以这样打电话
print_vector(std::cout, rotors[0].GetRotor());或者,您可以为<<提供一个重载,用于打印所有的Rotor。
std::ostream& operator<<(std::ostream&,const Rotor& rotor) {
out << rotor.position;
for (auto& i : rotor.GetRotor()) {
out << i;
}
// modify and add more to your likings
return out;
}一旦有了,您还可以提供一个重载来打印可以在Enigma::PrintRotor中使用的转子向量(目前只打印矢量的第一个元素):
std::ostream& operator<<(std::ostream& out,const std::vector<Rotor>& rotors) {
for (const auto& r : rotors) {
out << r << '\n';
}
return out;
}PS您的命名有点混乱。Rotor有一个返回permutations的GetRotor !?!我强烈建议用更好的名字。如果我有Rotor r;,那么r就是Rotor,还不清楚GetRotor会做什么。也许把它重命名为GetPermutations
https://stackoverflow.com/questions/60990293
复制相似问题