C ++将标准列表分成两个列表 [英] C++ split std list into two lists

查看:128
本文介绍了C ++将标准列表分成两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,所以我是C ++的新手,我遇到了这个问题,我想将一个std字符串列表拆分为两个列表.

Hey so I'm reasonably new into c++ and I ran into this problem where I want to split one std list of strings into two lists.

例如:list(1,2,3,4)-> list1(1,2) & list2(3,4)

我猜想splice是我应该使用的,但是我根本不明白它是如何工作的...

I guess splice is what I am supposed to use for this, but I could not understand how that works at all...

有人可以建议我该怎么做吗?
对不起,我的英语不好,谢谢大家的帮助.

Can someone please advice me how to do this?
Sorry about my bad English and thanks for help everyone.

推荐答案

我刚接触c ++"

对于具有Java或C#经验的用户来说,这是一个普遍的误解,因为std::list是他们语言中List的确切行为替代.实际上,对于上面提到的两个,在c ++中是std::vector.

It's a common misconception of users coming with Java or C# experience, that std::list is the exact behavioral replacement of List in their language. In fact for the mentioned two it's std::vector in c++.

我想将列表的一半拆分为一个列表,将另一半拆分为另一个列表."

您可以轻松地做到这一点,放弃std::list,并在可能的情况下切换到std::vector:

You can easily do this, giving up the std::list, and switch to a std::vector if possible:

#include <iostream>
#include <vector>

void print(const std::string name, const std::vector<int>& v) {
    std::cout << name << " = { ";
    bool first = true;
    for(auto i : v) {
        if(!first) {
            std::cout << ", ";
        }
        else {
            first = false;
        }
        std::cout << i;
    }
    std::cout << " }" << std::endl;
}

int main() {
    std::vector<int> master { 1, 2, 3, 4};

    size_t halfPos = master.size() / 2;

    if(halfPos > 0) {
        std::vector<int> firstPart(master.begin(),master.begin() + halfPos);
        std::vector<int> lastPart(master.begin() + halfPos,master.end());

        print("master",master);
        print("firstPart",firstPart);
        print("lastPart",lastPart);
    }
    return 0;
}


输出:


Output:

 master = { 1, 2, 3, 4 }
 firstPart = { 1, 2 }
 lastPart = { 3, 4 }

实时演示

如前所述,std::list::splice()具有完全不同的目的.

As mentioned std::list::splice() has a completely different purpose.

如果您确实需要std::list,则唯一的选择是进行迭代和计数. std::list::iterator不支持类似+ 的操作.

If you really need to have a std::list, your only option is to iterate and count. The std::list::iterator doesn't support operations like +.

这篇关于C ++将标准列表分成两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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