将列表插入到向量的末尾 [英] insert list to end of vector

查看:39
本文介绍了将列表插入到向量的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以将整个列表插入到向量的末尾而不插入前值并为整个列表弹出它?现在,我正在做事:

Is there an easy way to insert an entire list to the end of a vector without inserting the front value and popping it for the entire list? Right now, I'm doing thing:

std::vector<int> v({1,2,3});
std::list<int> l({5,7,9});
for (int i=0; i<3; i++) {
    v.push_back(l.front());
    l.pop_front();
}

我希望有某种方法可以轻松地遍历列表并将其插入到向量中.

I'm hoping for some way to easily just iterate through the list and insert it into the vector.

推荐答案

需要在v的末尾插入.vectorlist 都有迭代器,所以它非常简单.

You need to insert at the end of v. Both vector and list have iterators so its pretty straight forward.

你可以用这一行替换你的 for 循环:

You can replace your for loop with this single line:

v.insert(v.end(), l.begin(), l.end());

这是更新的代码:

#include <iostream>
#include <vector>
#include <list>

int main() {
    std::cout << "Hello, World!\n";
    std::vector<int> v({1,2,3});
    std::list<int> l({5,7,9});

    v.insert(v.end(), l.begin(), l.end());
    l.clear();

    for (int i : v) {
        std::cout << i << " ";
    }

    std::cout << std::endl;

    return 0;
}

输出:

Hello, World!
1 2 3 5 7 9 
Program ended with exit code: 0

这篇关于将列表插入到向量的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆