New learner working through a coding book and having trouble with an exercise problem. The exercise goal was practicing using the for() loop.
I'm trying to read two lines from a .txt file into two different vectors:
Text file:
0 1 1 2
0 1 1 2 3 5 8
Code I've written so far (very likely messy). In the end I couldn't get the vectors to load separately and ended up manually entering the vectors directly into the code, changing the numbers to match or not match, just to make sure I was doing the for() loop near the bottom correctly. I've currently commented out the manual vector entries, because I was trying unsuccessfully to find a solution to my dilemma:
// Exercise 5.17: Given two vectors of ints, write a program to determine whether one vector is a prefix of the other.
// For vectors of unequal length, compare the number of elements of the smaller vector.
// For example, given the vectors containing 0, 1, 1, and 2 and 0, 1, 1, 2, 3, 5, 8, respectively your program should return true.
#include <iostream>
#include <vector>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;
int main() {
//create two variables to hold vectors
vector<int> v1 /*{0, 1, 1, 2} */;
vector<int> v2 /*{0, 1, 1, 2, 3, 5, 8} */;
// read from console two lines of numbers into two different vectors
int n{};
// flag to change once a new line is read
bool flag = false;
// input file will only have two lines of only integers
while (cin >> n);{
if (n == '\n') // when a new line is seen, flip the flag
flag = true;
if (!flag) // read the first line of numbers into first vector until you see a new line
v1.push_back(n);
else // read the next line of numbers into second vector
v2.push_back(n);
}
// compare values of the vectors to flag this boolean
bool match = false;
if(v1.size() < v2.size()){ // if v1 is the smaller vector then compare its elements
for (decltype(v1.size()) index = 0; index != v1.size(); ++index){
if (v1[index] == v2[index])
match = true;
else
match = false;
}
}
else {
for (decltype(v2.size()) index = 0; index != v2.size(); ++index) { // if v2 is the smaller vector then compare its elements
if (v1[index] == v2[index])
match = true;
else
match = false;
}
}
// change boolean flag into 'true' or 'false'
string value;
if (match)
value = "true";
else
value = "false";
//print out the results
cout << "Do the two vectors match, or is vector 1 a prefix of vector 2: '\n'" << value << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire