Exercise 5.17:
Given two vectors of
int
s, 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.
This executes correctly, but I just want to get this double-checked.
#include <iostream>
#include <vector>
using std::vector; using std::cout; using std::endl;
int main()
{
vector<int> v1{ 0, 1, 1, 2, 3, 5, 8 };
vector<int> v2{ 0, 1, 1, 2 };
if (v1.size() < v2.size()){
cout << "Using v1 as the prefix to v2" << endl;
for (int smallIndex = 0, largeIndex = 1; smallIndex != v1.size(); ++smallIndex, ++largeIndex){
if (v1[smallIndex] == v2[largeIndex])
cout << "v1 at position " << smallIndex << " is a prefix for v2 at postion " << largeIndex << endl;
}
}
else if (v1.size() > v2.size()){
cout << "Using v2 as the prefix to v1" << endl;
for (int smallIndex = 0, largeIndex = 1; smallIndex != v2.size(); ++smallIndex, ++largeIndex){
if (v2[smallIndex] == v1[largeIndex])
cout << "v2 at position " << smallIndex << " is a prefix for v1 at position " << largeIndex << endl;
}
}
else { // v1.size() == v2.size() only comparing the first as the prefix to the second
cout << "Size of v1 and v2 are the same, using v1 as the prefix to v2" << endl;
for (int smallIndex = 0, largeIndex = 1; largeIndex != v1.size(); ++smallIndex, ++largeIndex){
if (v1[smallIndex] == v2[largeIndex])
cout << "v1 at position " << smallIndex << " is a prefix for v2 at postion " << largeIndex << endl;
}
}
}