c++ - 整数对 vector 到整数 vector vector

标签 c++

我怎么去

std::vector<std::pair<int, int>>

只是

std::vector<std::vector<int>>

?有真正有效的方法吗?

最佳答案

我会做这样的事情:

#include <vector>
#include <utility>

int main()
{
    //Vector of pairs
    std::vector<std::pair<int, int>> pairs = { {1,1},{2,2} };
    //New vector
    std::vector<std::vector<int>> vec;
    //Allocate memory for new vector
    vec.reserve(pairs.size());

    for (auto &p : pairs)
    {
        //Create vector with first and second element of pair
        std::vector<int> v = { p.first, p.second };
        vec.push_back(v);
    }

    return 0;
}

更新:为避免复制,您可以将 vector 移动到新 vector vec.push_back(std::move(v));

关于c++ - 整数对 vector 到整数 vector vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58636873/

相关文章:

c++ - 如何更改clang的预编译头文件路径

c++ - 从文本文件读取行到 std::vector<string> 的最有效方法

c++ - Vector size() 返回看似随机的大整数

还包括现有变量的 C++17 结构化绑定(bind)

c++ - 在 world.iprobe 上 boost MPI 崩溃

c++ - Scala宏和C++模板的异同

c++ - "2.00"和 "2.00f"之间是否存在功能差异?

c++ - 将整个程序构建为 FSM 的良好设计?

C++ 使用暂停/恢复控件下载文件

c++ - 奇怪的 c++ 变量声明错误,说一个类是它自己的私有(private)成员