題目:假設有兩個包含整數的vector對象,編寫一段程序,檢驗其中一個vector對象是否是另一個的前綴。爲了實現這一目標,對於兩個不等長
的vector對象,只需挑出長度較短的那個,把它的所有元素和另一個vector對象比較即可。
例如,如果兩個vector對象的元素分別是0、1、1、2 和0、1、1、2、3、5、8,則程序的返回結果應該爲真。
下面是我寫的,我現在看都覺得有點蠢,不知道以後看會不會羞憤而死。。。。。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> ivec1, ivec2;
int i,temp=1;
cout << "first number:" << endl;
cin >> i;
ivec1.push_back(i);
cout << "second number:" << endl;
cin >> i;
ivec2.push_back(i);
bool mix = (ivec1.size() > ivec2.size());
switch (mix)
{
case 0:
{
for (vector<int>::size_type t = 0; t != ivec1.size(); ++t)
{
if (ivec1[t] == ivec2[t])
++temp;
else
break;
}
if (temp == ivec1.size())
cout << "yes" << endl;
else
cout << "no" << endl;
break;
}
case 1:
{
for (vector<int>::size_type t = 0; t != ivec2.size(); ++t)
{
if (ivec2[t] == ivec1[t])
++temp;
else
break;
}
if (temp == ivec2.size())
cout << "yes" << endl;
else
cout << "no" << endl;
break;
}
}
return 0;
}