C++:问题向量 STL.
C++:questions vector STL
我通过调用名为 getDivisors
的函数并返回由容器vector<int>
格式化的值来获取除数。
由于我是C++
容器的新手,因此我尝试使用迭代器通过 for 循环打印除数整数。但是,在我看来,这似乎太复杂了。有没有简单的方法可以在向量STL
中显示存储的整数?
我不明白为什么迭代器变量it is pointer type? Could you explain it more about it? I was confused that the compilers show the error message when I did
它not
它"
以下是我的简单代码。
#include <iostream>
#include <vector>
using namespace std;
vector<int> getDivisors(int input)
{
vector<int> divisors;
divisors.push_back(1); //default
for (int i = 2; i < input; i++){
if (input%i == 0){
divisors.push_back(i);
}
}
return divisors;
}
void solve()
{
int input;
cin >> input;
vector<int> divisors = getDivisors(input);
for (vector<int>::iterator it = divisors.begin(); it != divisors.end(); ++it)
{
cout << *it << endl;
}
}
int main(void)
{
int num;
cin >> num;
for (int i = 0; i < num; i++){
solve();
}
return 0;
}
你没有提到你正在使用哪个编译器,但在C++11兼容编译器中,你可以使用auto和基于范围的for循环
for (auto i : divisors)
{
cout << i << endl;
}
i
这里不是迭代器,而是容器模板类型,在您的情况下是int
指针是一种迭代器,特别是随机访问迭代器。迭代器被设计为指针的抽象,带有*
、->
、++
、--
等运算符来访问容器。
对于C++程序员来说,cplusplus.com 是你的朋友。
它不是一个指针,它是一个迭代器。它重写operator *
以提供类似指针的行为。您可以阅读有关C++STL的更多信息来理解这一点。
如果您使用的是 C++11 或更高版本,请使用以下命令:
for (auto x : divisors) cout << x << endl;
迭代器是方便的抽象,有助于访问容器。它们不是指针。
您必须注意的一件事是,如果与之关联的容器发生重大更改,迭代器可能会失效。
在继续之前,先读一本关于STL的好书,并掌握正确的基础知识。这是一个入门,但它只能做这么多。
http://www.cprogramming.com/tutorial/stl/iterators.html
- 具有 STL 向量类型成员的类的复制内存
- STL 向量无缘无故损坏,VC++ 2017
- 如何避免自定义 STL 向量类的智能指针 delete[] 异常?
- STL向量上出现奇怪的复制构造函数错误
- OpenMP 和不同的 STL 向量
- C++ STL 向量保留太多容量会消耗大量内存吗?
- 使用 boost Spirit 解析为 STL 向量
- C++ 在列表末尾插入元素的列表的 STL 向量
- C++ 使用数组初始化时的 STL 向量内存管理
- 仅编写 c++ stl 向量的第一个元素的正确方法
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 限制指针访问STL ::向量元素
- 传递包裹在shared_ptr中的 STL 向量
- 如何将结构指针插入stl向量中并显示内容
- 将一个STL向量有效地分配给另一个STL矢量(WSL问题)
- erase() 不适用于结构/对象内的 STL 向量
- STL向量具有反向和pop/push_back成本
- 获取 STL 向量C++的地址
- Unique_ptr的 STL 向量 - 如何重置
- 带有 STL 向量的模板函数会因新的分配器而中断