两道挺有意思的基础题

来源:互联网 发布:淘宝特卖女装清仓棉袄 编辑:程序博客网 时间:2024/06/15 20:19

主要是之前没见过pair 所以mark一下

1002. 求向量的第k个元素(k任意)

Description

pair<int, bool> selectVector_ith2(const vector<int> & L, int k)

/* 返回一个二元组(a, b): 如果k大于0,小于等于L的长度,a是L中的第k个元素, b = true,否则, a= 0, b= false。函数返回L的第k个元素。例,L=(3,5,4,2),当k=1时返回(3, true),当k=4时返回(2, true), 当k>4或者k<=0时,a=0, b=false.

*/

{

    //填写代码,测试后提交。只需提交该函数的实现。

}

Problem Source: Vector与List练习(相当简单)




#include<iostream>#include<vector>using namespace std;pair<int, bool> selectVector_ith2(const vector<int> & L, int k){    vector<int> J;    J.assign(L.begin(),L.end());    if(k>0&&k<=J.size())    return make_pair(J[k-1],true);    else    return make_pair(0,false);}                                 


1003. 求链表的第k个元素(k任意)

Description

pair<int, bool> selectList_ith2(const list<int>  &L, int k)

// 返回一个二元组(a, b): 如果k大于0,小于等于L的长度,a是L中的第k个元素, b = true,否则, a= 0, b= false。函数返回L的第k个元素。例,L=(3,5,4,2),当k=1时返回(3, true),当k=4时返回(2, true), 当k>4或者k<=0时,a=0, b=false.

{

    //填写代码,测试后提交。只需提交该函数的实现。

}

 

 

Problem Source: Vector与List练习(相当简单)




#include<iostream>
#include<list>
using namespace std;
pair<int, bool> selectList_ith2(const list<int> &L, int k)
{
int count=0;
if(k>L.size()||k<=0)
for(list<int>::const_iterator i=L.begin();i!=L.end();i++)
return make_pair(0,false);
{
count++;
}
if(count==k)
{
return make_pair(*i,true);
}
}




睡了 晚安


原创粉丝点击