patterncppModerate
Determine whether one vector is a prefix of the other
Viewed 0 times
theonedetermineprefixotherwhethervector
Problem
Exercise 5.17:
Given two vectors of
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.
Given two vectors of
ints, write a program to determinewhether 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
#include
using std::vector; using std::cout; using std::endl;
int main()
{
vector v1{ 0, 1, 1, 2, 3, 5, 8 };
vector v2{ 0, 1, 1, 2 };
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;
}
}
}Solution
For a prefix search, you can use
std::mismatch() in ``.bool isPrefix(const std::vector& v1, const std::vector& v2) {
if (v1.size() > v2.size()) {
return v2.end() == std::mismatch(v2.begin(), v2.end(), v1.begin()).first;
}
return v1.end() == std::mismatch(v1.begin(), v1.end(), v2.begin()).first;
}Code Snippets
bool isPrefix(const std::vector<int>& v1, const std::vector<int>& v2) {
if (v1.size() > v2.size()) {
return v2.end() == std::mismatch(v2.begin(), v2.end(), v1.begin()).first;
}
return v1.end() == std::mismatch(v1.begin(), v1.end(), v2.begin()).first;
}Context
StackExchange Code Review Q#60144, answer score: 10
Revisions (0)
No revisions yet.