【发布时间】:2018-02-05 20:52:17
【问题描述】:
我有一个尽可能简化的类并用于演示目的。它看起来很简单:
#include <iostream>
#include <vector>
class Simple
{
private:
std::vector<std::size_t> indices;
std::vector<int> values;
public:
void insert(std::size_t index, int value)
{
indices.push_back(index);
values.push_back(value);
}
int at(std::size_t index)
{
return values[indices[index]];
}
};
int main()
{
Simple s;
s.insert(10, 100);
std::cout << s.at(10) << std::endl;
return 0;
}
我要实现的是迭代此容器的元素并在每次迭代时获取 std::pair,其first 元素将是来自indices 成员的值,其second 元素将是一个值来自values 成员。比如:
Simple s;
s.insert(10, 100);
for (std::pair<std::size_t, int> node : s)
{
std::cout << node.first << " " << node.second << std::endl; // expect to print 10 100
}
我对迭代器真的很陌生。我知道如何遍历标准容器并获取它们的值。我什至知道如何遍历我的Simple 容器并在每次迭代时从values 成员中获取价值。我可以这样做:
//new member functions in Simple class
auto begin()
{
std::begin(values);
}
auto end()
{
std::end(values);
}
但我不知道如何在每次迭代中创建一些新的数据类型并将其返回给客户端代码。
【问题讨论】:
-
main中的示例代码将产生未定义的行为。看起来您正在尝试制作地图,但没有完全正确。您不只是使用 STL 地图有什么原因吗? -
我知道它看起来像地图,但正如我所说,我做了一个简单的例子只是为了演示。
-
这就是你要找的,也许是:stackoverflow.com/questions/8511035/…
-
@Rakete1111。类似的东西,但没有提升依赖关系。
-
基于range 的答案没有得到提升。它甚至可能在您的标准库中为
std::experimental::ranges
标签: c++