c++ primer 3.5.3节练习答案

练习3.34 p1=p1+(p1-p2) ,即将p1指针向前(向后)移动p1-p2个位置,当p1是常量指针时,程序非法,因为程序尝试改变p1所指向的元素。

练习3.35

int main()
{
 int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
 int *beg = begin(a);
 int *last = end(a);
 while (beg != last)
 {
  *beg = 0;
  beg++;
 }
 for (auto c : a)
  cout << c << " ";
 system("pause");
 return 0;
}

练习3.36

数组

int main()
{
 int a[10] = { 1,2,3,4,5 };
 int b[10] = { 1,2,3,4,5 };
 int *beg1 = begin(a);
 int *last1 = end(a);
 int *beg2 = begin(b);
 int *last2 = end(b);
 if ((last2 - beg2) != (last1 - beg1))
  cout << "error" << endl;
 else
 {
  while (beg1 != last1 && beg2 != last2)
  {
   if (*beg1 != (*beg2))
   {
    cout << "error" << endl;
    break;
   }
   else
   {
    beg1++;
    beg2++;
    if (beg1 == last1 && beg2 == last2)
     cout << "equal" << endl;
   }  
  }
 }
 system("pause");
 return 0;
}

vector

int main()
{
 vector<int> a1{10, 20, 30};
 vector<int> a2{ 10,20,30 };
 if (a1.size() != a2.size())
  cout << "error" << endl;
 else
 {
  for (auto i = 0; i != a1.size();)
  {
   if (a1[i] != a2[i])
   {
    cout << "error" << endl;
    break;
   }
   else
   {
    i++;
    if (i = a1.size())
     cout << "equal" << endl;
   }
  }
 }
 system("pause");
 return 0;
}

posted @ 2017-07-27 16:09  五月份小姐  阅读(404)  评论(0)    收藏  举报