c++ - 创建 const std::vector 作为两个 const std::vector 的串联

标签 c++ templates stl constants declaration

我想创建一个 const std::vector 来包含其他两个相同类型的 const std::vector 的所有元素。由于 vector 是 const 我无法使用 Concatenating two std::vectors 中提到的方法将它与两个 const std::vector 逐步连接起来.

#include <iostream>
#include <vector>

int main()
{
    const std::vector<int> int_a{0,1};
    const std::vector<int> int_b{2,3};
    const std::vector<int> all_ints;
    
    for (int i: all_ints)
        std::cout << i << ' ';
    return 0;
}

对于上面的示例,我想以输出为 0 1 2 3 的方式定义 all_ints

那怎么可能呢?

最佳答案

创建一个函数,接受另外两个 vector ,创建第三个 vector ,插入前两个 vector 的值,按值返回结果。然后将其分配给您的 const vector :

const std::vector<int> int_a{0,1};
const std::vector<int> int_b{2,3};
const std::vector<int> all_ints = concat(int_a, int_b);

关于c++ - 创建 const std::vector 作为两个 const std::vector 的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74375751/

相关文章:

c++ - IEEE754 float 在多大程度上满足 LessThanComparable?

c++ - 在 C++ 中使用第二个索引数组对数组进行排序

c++ - 是否可以使用模板来识别两种不同的类型?

c++ - 通过 for 循环从 C++ 映射中删除元素

c++ - 将 libssh 导入 Qt

c++ - 在 C++ 中连接字符串时出错

模板类上的 C++ 模板复制构造函数

c++ - 在编译时将类型转换为整数?

c++ - std::vector.pop_back() 会改变 vector 的容量吗?

C++:使用STL vector有什么错误