消除集合的第一个元素

displaing the first elements of set

本文关键字:第一个 元素 集合      更新时间:2023-10-16

我尝试显示std::set的第一个元素。每次我都想显示剩余的元素。

例如一个集合:4 6 8 9 .

  • 第一个元素是4集合的其余元素是6 8 9

  • 前两个元素4 6其余元素8 9

  • 那么前三个元素4, 6, 8其余的:9 .

我开始的代码:

for (std::set<int>::iterator it = my_set.begin(); it != my_set.end(); ++it)
{
        std::vector<decltype(*it)> items((my_set.begin()), *it);
        // items is a vector containing successively the n first elements
}

使用此代码,我有错误,并且在显示第一个元素后无法拥有集合的其余部分。 你可以帮我吗?

您正在寻找的向量构造函数是采用迭代器的构造函数:

std::vector<std::decay_t<decltype(*it)>> items(my_set.begin(), it);

但是你不需要中间std::vector,你可以直接使用范围(使用迭代器( 您可以使用如下内容:

template <typename IT>
void print(IT begin, IT end)
{
    const char* sep = "";
    for (auto it = begin; it != end; ++it) {
        std::cout << sep << *it;
        sep = ",";
    }
}
int main()
{
    std::set<int> s{4, 6, 8, 9};
    for (auto it = std::next(s.begin()); it != s.end(); ++it) {
        std::cout << "First elements: "; print(s.begin(), it);
        std::cout << ", Rest: "; print(it, s.end()); std::cout << std::endl;   
    }
}

演示

如果你想要第一个元素和其余元素N独立的函数:

#include <set>
#include <iostream>
using namespace std;
template<typename T>
void printHead(set<T>& mySet, unsigned int position) {
    for (auto it = mySet.begin(); it != next(mySet.begin(), position); it++) {
        cout << *it << ' ';
    }
    cout << endl;
}
template<typename T>
void printTail(set<T>& mySet, unsigned int position) {
    for (auto it = next(mySet.begin(), position); it != mySet.end(); it++) {
        cout << *it << ' ';
    }
    cout << endl;
}
int main(void) {
    set<int> foo{0, 1, 2, 3, 4, 5, 6, 7};
    const auto N = 3;
    cout << "First " << N << " elements: ";
    printHead(foo, N);
    cout << "The rest: ";
    printTail(foo, N);
}