我创建了一个集合,我想提供一个STL风格的随机访问迭代器.我正在寻找迭代器的示例实现,但我没有找到任何.我知道需要const重载[]和*运算符.迭代器有什么要求是"STL风格",还有哪些其他缺陷需要避免(如果有的话)?
附加上下文:这是一个库,除非我真的需要,否则我不想引入任何依赖.我编写自己的集合,以便能够使用相同的编译器在C++ 03和C++ 11之间提供二进制兼容性(因此没有STL可能会破坏).
我写了一个OutputIterator来回答另一个问题.这里是:
#include <queue>
using namespace std;
template< typename T, typename U >
class queue_inserter {
queue<T, U> &qu;
public:
queue_inserter(queue<T,U> &q) : qu(q) { }
queue_inserter<T,U> operator ++ (int) { return *this; }
queue_inserter<T,U> operator * () { return *this; }
void operator = (const T &val) { qu.push(val); }
};
template< typename T, typename U >
queue_inserter<T,U> make_queue_inserter(queue<T,U> &q) {
return queue_inserter<T,U>(q);
}
Run Code Online (Sandbox Code Playgroud)
这适用于这个小复制功能:
template<typename II, typename OI>
void mycopy(II b, II e, OI oi) {
while …Run Code Online (Sandbox Code Playgroud) 我有一个"列"容器类型:
struct MyColumnType {
// Data: Each row represents a member of an object.
vector<double> a; // All vectors are guaranteed to have always
vector<string> b; // the same length.
vector<int> c;
void copy(int from_pos, int to_pos); // The column type provides an interface
void swap(int pos_a, int pos_b); // for copying, swapping, ...
void push_back(); // And for resizing the container.
void pop_back();
void insert(int pos);
void remove(int pos);
// The interface can be extended/modified if required
};
Run Code Online (Sandbox Code Playgroud)
用法: …
我想设计一个类Foo来存储不同类型的各种数据并返回它们的迭代器。它应该是通用的,因此用户Foo不知道数据是如何存储的(Foo可能正在使用std::set或std::vector其他)。
我很想写一个这样的界面:
class Foo {
class FooImpl;
FooImpl* impl_;
public:
const Iterator<std::string>& GetStrings() const;
const Iterator<int>& GetInts() const;
};
Run Code Online (Sandbox Code Playgroud)
哪里Iterator有类似这样的东西(比如 .NET 中的迭代器):
template<class T>
class Iterator {
public:
const T& Value() const = 0;
bool Done() const = 0;
void Next() = 0;
};
Run Code Online (Sandbox Code Playgroud)
但我知道这种迭代器在C++中不是标准的,最好像STL那样使用迭代器,这样你就可以在它们上使用STL算法。
我怎样才能做到这一点?(我有需要iterator_traits吗?)
使用for_each迭代NULL终止的字符串是可能的:
const char *name = "Bob";
void func(const char &arg)
{
cout << arg;
}
int main()
{
for_each(name, name + strlen(name), func);
}
Run Code Online (Sandbox Code Playgroud)
对于NULL终止的字符串列表,可能类似的事情(不必首先确定列表的总长度),例如:
const char *names[] = { "Bob", "Adam", "Simon", NULL };
Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个类,它允许我迭代对象STL样式而不将它们显式存储在容器中.
例如,一个简化的例子是,<Paragraph>::iterator在一个实际上没有Paragraph容器的类中,而是有一个<string> text变量.创建一个实际通过逐行文本并组装段落的成员函数很容易,但是对于我来说,将所有这些文本再次存储在某个容器中似乎很愚蠢,以便我可以继承它的迭代器.
另外,我把它称为a <Paragraph>::iterator而不是a <string>::iterator的原因是因为我可能想要一个不同类型的迭代器.例如,我可以计算每个段落中的字符数,并有一个<int>::iterator.
我想我的问题是:在没有容器的情况下考虑迭代器是否合适?
谢谢
我如何insert()将一堆物品deque放在线性时间的中间?
(我插入的项目无法通过STL样式的迭代器访问.)
我知道它是许多编程语言中的一种常见模式(主要是功能性的),但我不确切地知道它是如何调用的.所以我有一个数据结构,例如列表A和其他列表B.列表A包含一些值(中文字符串),我想将这些字符串映射到列表B,将它们翻译成英语.所谓的地图和变异.有人可以告诉我这个模式是如何正确命名的,并在objective-C,Java,Haskell等中给出一些指向它的实现的链接.