如何遍历shared_ptr<std::vector<int>>?请帮忙完成foo函数实现
解决方案
你已经通过std::static_pointer_cast完成了从std::shared_ptr<void>到std::shared_ptr<std::vector<int>>的类型转换,接下来只需要遍历容器并打印元素即可。
完整的foo()函数实现如下:
void foo(std::shared_ptr<void> input) { // 将void类型智能指针转换回vector<int>类型 auto sp_vec = std::static_pointer_cast<std::vector<int>>(input); // 遍历vector并打印所有元素 for (int num : *sp_vec) { std::cout << num << " "; } std::cout << std::endl; }
关键说明
std::static_pointer_cast的使用是安全的,因为我们明确知道原始指针指向的是std::vector<int>类型。如果类型不匹配,这种转换会触发未定义行为,必须保证转换目标类型与原始类型完全一致。- 遍历方式可以选择C++11引入的范围for循环,代码简洁直观;也可以用传统的下标或迭代器遍历:
// 下标遍历示例 for (size_t i = 0; i < sp_vec->size(); ++i) { std::cout << (*sp_vec)[i] << " "; } - 注意需要包含
<iostream>头文件才能使用std::cout输出内容。
完整可运行的测试代码:
#include <iostream> #include <vector> #include <memory> void foo(std::shared_ptr<void> input) { auto sp_vec = std::static_pointer_cast<std::vector<int>>(input); for (int num : *sp_vec) { std::cout << num << " "; } std::cout << std::endl; } int main() { std::vector<int> myIntVec = { 1, 2, 3, 4}; auto mBlock = std::make_shared<std::vector<int>>(myIntVec); std::shared_ptr<void> in = std::static_pointer_cast<void>(mBlock); foo(in); return 0; }
运行后会输出:1 2 3 4
内容的提问来源于stack exchange,提问作者SK17
相关产品推荐
相关产品推荐

