首页 新闻 会员 周边

C++编写函数!大神求解释!!!

0
悬赏园豆:100 [已关闭问题] 关闭于 2017-03-04 20:02

如何使用swap和vector<string>编写两个函数,反转一个vector<int>类型向量中的元素顺序。第一个反转函数生成新向量,其中元素为原向量的逆序,而原向量内容不变。另一个反转函数不使用任何其他向量。例如1、2、3转换为3、2、1。

大神呐,我刚刚学不会解这道题啊~!

GGGYMg的主页 GGGYMg | 初学一级 | 园豆:103
提问于:2016-12-26 23:03
< >
分享
所有回答(2)
0
// reverse algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::reverse
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector;

  // set some values:
  for (int i=1; i<10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9

  std::reverse(myvector.begin(),myvector.end());    // 9 8 7 6 5 4 3 2 1

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

 

CaiYongji | 园豆:1267 (小虾三级) | 2016-12-27 09:51

你能告诉我哪里是使用了swap吗?

支持(0) 反对(0) GGGYMg | 园豆:103 (初学一级) | 2016-12-27 12:31
0

http://www.cplusplus.com/reference/algorithm/swap/

 1 // swap algorithm example (C++98)
 2 #include <iostream>     // std::cout
 3 #include <algorithm>    // std::swap
 4 #include <vector>       // std::vector
 5 
 6 int main () {
 7 
 8   int x=10, y=20;                              // x:10 y:20
 9   std::swap(x,y);                              // x:20 y:10
10 
11   std::vector<int> foo (4,x), bar (6,y);       // foo:4x20 bar:6x10
12   std::swap(foo,bar);                          // foo:6x10 bar:4x20
13 
14   std::cout << "foo contains:";
15   for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
16     std::cout << ' ' << *it;
17   std::cout << '\n';
18 
19   return 0;
20 }

这个网址会对你有很大帮助

武装三藏 | 园豆:114 (初学一级) | 2016-12-30 09:51
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册