如何实现可迭代结构?
How do I implement an iterable structure?
我想写一个可以循环的结构。为此,我添加了两个方法 begin 和 end ,它们将 return begin, end values of an already existing vector。我应该指定什么 return 类型,这两种方法是否足以使 MATCH 结构在我的上下文中工作?到目前为止,这是我得到的:
typedef std::pair<std::string, std::string> combo;
struct MATCH {
std::vector<combo> matches;
? begin() { return matches.begin(); }
? end() { return matches.end(); }
};
int main() {
MATCH m = { ... };
for (const combo& i : m)
...;
}
我认为您要寻找的类型是 std::vector<combo>::iterator
。
示例:
typedef std::pair<std::string, std::string> combo;
struct MATCH {
std::vector<combo> matches;
std::vector<combo>::iterator begin() { return matches.begin(); }
std::vector<combo>::iterator end() { return matches.end(); }
};
int main()
{
MATCH m = { { {"something", "something"} } };
for (const combo& i : m)
cout << i.first << " " << i.second << std::endl;
return 0;
}
我想写一个可以循环的结构。为此,我添加了两个方法 begin 和 end ,它们将 return begin, end values of an already existing vector。我应该指定什么 return 类型,这两种方法是否足以使 MATCH 结构在我的上下文中工作?到目前为止,这是我得到的:
typedef std::pair<std::string, std::string> combo;
struct MATCH {
std::vector<combo> matches;
? begin() { return matches.begin(); }
? end() { return matches.end(); }
};
int main() {
MATCH m = { ... };
for (const combo& i : m)
...;
}
我认为您要寻找的类型是 std::vector<combo>::iterator
。
示例:
typedef std::pair<std::string, std::string> combo;
struct MATCH {
std::vector<combo> matches;
std::vector<combo>::iterator begin() { return matches.begin(); }
std::vector<combo>::iterator end() { return matches.end(); }
};
int main()
{
MATCH m = { { {"something", "something"} } };
for (const combo& i : m)
cout << i.first << " " << i.second << std::endl;
return 0;
}