消除集合的第一个元素
displaing the first elements of set
我尝试显示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);
}
相关文章:
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- C++ queue.front();为什么不从第一个元素开始呢?
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 静态堆栈函数不会 1) 输入第一个元素 2)添加新元素时识别旧元素
- 从队列中删除第一个元素C++
- 如果第一个元素包含任何零,则我的程序以不希望的方式运行
- 为什么数组不打印第一个元素?
- 在数组中显示第一个元素用户输入
- 消除集合的第一个元素
- 为什么指向矢量第一个元素的指针会丢失?
- 如何打印出常量字符串的第一个元素?
- 读取数组的第一个元素还是第 4000 个元素更快?
- 如何在数组的一部分中查找特定值的第一个元素
- 对数组进行排序的算法,先是第一个元素,然后是前 2 个元素,然后是前 3 个元素,依此类推
- 访问指向对象指针向量的指针的第一个元素?
- 引用保留向量中的第一个元素
- 指向数组的指针是否应该等于指向其第一个元素的指针?
- 尝试将参数包的第一个元素作为函数调用,并将包的其余部分作为参数传递给它
- 代码是否有效.如果我想显示第一个元素?如果不是,那么 s.begin() 会返回什么?