本帖最后由 bin554385863 于 2019-10-6 13:52 编辑
这个题是考察对容器操作的掌握
如果能熟练操作容器相关函数以及排序算法,这个问题一点都不难!
另外对容器增加元素时最好使用push_back()函数,而不是使用下标.#include <iostream>
#include<algorithm>
#include <vector>
void merge(std::vector<int> &nums1, int m, std::vector<int> &nums2, int n)
{
if( (m > nums1.size())||(n > nums2.size()))
{
exit(0);
}
nums1.erase(nums1.begin() + m, nums1.end());//擦除元素erase(begin, end)/erase(pos)函数
nums2.erase(nums2.begin() + n, nums2.end());//擦除元素
for(int i:nums2)
{
nums1.push_back(i);//合并容器
}
sort(nums1.begin(), nums1.end());//排序sort(begin, end, less<datetype>(降序)/greater<datetype>(升序))
}
int main(int argc, char const *argv[])
{
std::vector<int> i = {0,1,2,3,9,10,11,0,0,0,0};
std::vector<int> j = {4,5,6,7,23,54,0,0,0,0};
merge(i,3,j,2);
for(int k:i)
{
std::cout<<k;
}
return 0;
}
---------------------------------------------------------------------------------------
E:\Users\86184\Documents\Code>c:\Users\86184\.vscode\extensions\ms-vscode.cpptools-0.25.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-h1fynkur.lkj --stdout=Microsoft-MIEngine-Out-5krajmjw.k3n --stderr=Microsoft-MIEngine-Error-hbeytjdn.g0o --pid=Microsoft-MIEngine-Pid-twavuu23.nog "--dbgExe=E:\My Program\MinGW\bin\gdb.exe" --interpreter=mi
01245
E:\Users\86184\Documents\Code>
------------------------------------------------------------------------
执行结果:
通过
显示详情
执行用时 :
8 ms
, 在所有 C++ 提交中击败了
77.81%
的用户
内存消耗 :
8.6 MB
, 在所有 C++ 提交中击败了
89.69%
的用户
容器最基本的操作增察删改 |