You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中创建可同时存储int和string类型的vector?

C++ 实现可存储int和string类型的vector方案
  • 如果你使用的是C++17或更高版本,优先使用std::variant,这是类型安全的多类型存储方案,符合你需求的写法示例如下:
#include <vector>
#include <variant>
#include <string>
#include <iostream>

int main() {
    // 定义可存储int或std::string的元素类型
    using Element = std::variant<int, std::string>;
    std::vector<Element> arr;
    
    // 存入数据的逻辑和你示例的写法完全对齐
    arr.push_back(4);
    arr.push_back("HELLO");
    
    // 读取元素的示例
    for (const auto& item : arr) {
        if (std::holds_alternative<int>(item)) {
            std::cout << "int值:" << std::get<int>(item) << std::endl;
        } else if (std::holds_alternative<std::string>(item)) {
            std::cout << "string值:" << std::get<std::string>(item) << std::endl;
        }
    }
    return 0;
}
  • 如果你使用的C版本低于C17,可以通过自定义多态类实现,写法示例如下:
#include <vector>
#include <string>
#include <iostream>
#include <memory>

// 所有元素的基类
class BaseObj {
public:
    virtual ~BaseObj() = default;
};

// 存储int的派生类
class IntObj : public BaseObj {
public:
    int val;
    IntObj(int v) : val(v) {}
};

// 存储string的派生类
class StringObj : public BaseObj {
public:
    std::string val;
    StringObj(const std::string& v) : val(v) {}
};

int main() {
    std::vector<std::unique_ptr<BaseObj>> arr;
    arr.push_back(std::make_unique<IntObj>(4));
    arr.push_back(std::make_unique<StringObj>("HELLO"));
    
    // 读取元素的示例
    for (const auto& item : arr) {
        if (auto intP = dynamic_cast<IntObj*>(item.get())) {
            std::cout << "int值:" << intP->val << std::endl;
        } else if (auto strP = dynamic_cast<StringObj*>(item.get())) {
            std::cout << "string值:" << strP->val << std::endl;
        }
    }
    return 0;
}
  • 不推荐方案:使用void*或者C风格union存储,这两种方案没有内置类型安全检查,极易出现内存泄漏、非法访问等问题,无特殊需求不要使用。

内容的提问来源于stack exchange,提问作者Sirop4ik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:45:03