Last active
December 10, 2015 03:58
-
-
Save id-0x76adf1/4377380 to your computer and use it in GitHub Desktop.
Determine whether one of the two vectors of ints is the prefix of the other.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <vector> | |
| typedef std::vector<int> int_vec; | |
| // the size of ivec1 is less than or equal to the size of ivec2 | |
| static bool is_prefix_impl(const int_vec& ivec1, const int_vec& ivec2) | |
| { | |
| auto it1 = ivec1.begin(); | |
| auto it2 = ivec2.begin(); | |
| for (; it1 != ivec1.end(); ++it1, ++it2) | |
| { | |
| if (*it1 != *it2) | |
| { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| bool is_prefix(const int_vec& ivec1, const int_vec& ivec2) | |
| { | |
| if (ivec1.size() <= ivec2.size()) | |
| { | |
| return is_prefix_impl(ivec1, ivec2); | |
| } | |
| return is_prefix_impl(ivec2, ivec1); | |
| } | |
| int main(int arc, char* argv[]) | |
| { | |
| int_vec ivec1; | |
| ivec1.push_back(0); | |
| ivec1.push_back(1); | |
| int_vec ivec2; | |
| ivec2.push_back(0); | |
| ivec2.push_back(1); | |
| ivec2.push_back(2); | |
| std::cout << std::boolalpha; | |
| std::cout << is_prefix(ivec1, ivec2) << std::endl; | |
| std::cout << is_prefix(ivec2, ivec1) << std::endl; | |
| ivec1.clear(); | |
| ivec2.clear(); | |
| ivec1.push_back(1); | |
| ivec1.push_back(0); | |
| ivec2.push_back(0); | |
| ivec2.push_back(1); | |
| ivec2.push_back(2); | |
| std::cout << is_prefix(ivec1, ivec2) << std::endl; | |
| std::cout << is_prefix(ivec2, ivec1) << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment