面试题答案
一键面试#include <iostream>
#include <vector>
#include <list>
#include <type_traits>
// 模板函数声明
template<typename Container1, typename Container2>
const auto addContainers(const Container1& c1, const Container2& c2) ->
typename std::enable_if<
std::is_same<typename Container1::value_type, typename Container2::value_type>::value,
std::vector<typename Container1::value_type>
>::type;
// 模板函数实现
template<typename Container1, typename Container2>
const auto addContainers(const Container1& c1, const Container2& c2) ->
typename std::enable_if<
std::is_same<typename Container1::value_type, typename Container2::value_type>::value,
std::vector<typename Container1::value_type>
>::type {
using value_type = typename Container1::value_type;
std::vector<value_type> result;
auto it1 = c1.begin();
auto it2 = c2.begin();
while (it1 != c1.end() && it2 != c2.end()) {
result.push_back(*it1 + *it2);
++it1;
++it2;
}
return result;
}
代码实现思路
- 模板参数:
Container1
和Container2
分别表示两个不同类型的容器。 - 类型兼容性检查:使用
std::is_same
来检查两个容器的元素类型是否相同,通过std::enable_if
来确保只有当元素类型相同时函数才会实例化。这样可以避免在元素类型不兼容时进行非法的加法操作。 - 返回类型推导:使用
auto
和decltype
结合std::enable_if
来推导返回类型。这里返回类型是std::vector<typename Container1::value_type>
,即一个与输入容器元素类型相同的std::vector
。 - 操作过程:遍历两个容器,将对应位置的元素相加,并将结果存入新的
std::vector
中。 - 常引用返回值:返回的是一个新创建的
std::vector
对象,由于函数返回的是一个局部对象的副本,这里不存在引用折叠和生命周期延长的问题,因为返回的不是引用而是对象本身。如果要返回引用,那么必须保证返回的引用所指向的对象在函数结束后仍然存在,比如返回传入的容器的引用,但这不符合本题创建新容器的要求。
在实际调用中:
int main() {
std::vector<int> v = {1, 2, 3};
std::list<int> l = {4, 5, 6};
const auto& result = addContainers(v, l);
for (auto num : result) {
std::cout << num << " ";
}
return 0;
}
上述代码中,addContainers
函数接受两个不同类型的容器,检查元素类型兼容性后,将对应元素相加并返回新的 std::vector
。在 main
函数中演示了该函数的调用。