我试图用迭代器滚动一个二维列表,我知道我错过了一些但我不知道是什么。
所以我的想法就是要解析一些命令。
我把它们放在一个列表上,然后我想检查一下列表中的成员是否等于“data.txt”。所以我为此做了一个迭代器,但由于它是一个内部有std :: pair的二维列表,我不知道如何实现这个迭代器。我做了这个,但它不好,我无法阅读这两个列表。
typedef std::list<std::string> listStr;
std::list <std::pair<listStr, int> > _execCmd;
int Parser::execCmd()
{
std::list<std::string>::const_iterator i;
for (i = _execCmd.front().first.begin(); i != _execCmd.back().first.end(); ++i)
{
if (*i == "Search.txt")
execSearch();
else if (*i == "data.txt")
execData();
}
return (0);
}
在这种情况下,我留在第一个列表“File.txt data.txt contact.txt”(cf:schema),我可以浏览第二个列表“Search.txt employe.csv”。
我也试过这个:
int Parser::execCmd()
{
std::list<std::pair<listStr, int> >::const_iterator i;
for (i = _execCmd.begin(); i != _execCmd.end(); ++i)
{
if (*i == "Search.txt")
execSearch();
else if (*i == "data.txt")
execData();
}
return (0);
}
但是我无法编译这个因为我不知道如何将迭代器与字符串进行比较(*i == "help"
)
有人可以帮帮我吗?
一个std::pair<X,Y>
包含两个成员,first
获得X
类型的成员和second
获得Y
类型的成员。
在你的情况下,由于typedef
你有一个std::list<std::pair<std::list<std::string>, int> >
。
因此,要迭代该结构中的所有std::string
s,您需要遍历外部列表以获取对,从每个(first
类型)中获取std::list<string>
成员,并迭代该内部列表的ever元素。
int Parser::execCmd()
{
std::list<std::pair<listStr, int> >::const_iterator i;
for (i = _execCmd.begin(); i != _execCmd.end(); ++i)
{
// i->first is of type std::list<std:string>
for (j = i->first.begin(); j != i->first.end(); ++j)
{
if (*j == "Search.txt")
execSearch();
else if (*j == "data.txt")
execData();
}
}
return (0);
}
在C ++ 11中,它更简单,但仍然需要嵌套循环。
int Parser::execCmd()
{
std::list<std::pair<listStr, int> >::const_iterator i;
for (const auto &i : _execCmd))
{
// i.first is of type std::list<std:string>
for (const auto &j : i.first)
{
if (j == "Search.txt")
execSearch();
else if (j == "data.txt")
execData();
}
}
return (0);
}
正如我在评论中所说,在c ++中迭代std::list
的方法是使用foreach语法。
迭代器的想法是为您提供对容器中元素的指针式访问,并为容器提供对这些元素进行操作的方法。例如,给定迭代器,您可以删除列表中的元素。或者您可以在特定位置插入元素。
但是,您需要遍历列表元素并检查是否存在“search.txt”或“data.txt”。所以你不需要任何迭代器,你只需要元素。这就是c ++中基于范围的for循环。 (看看这个很棒的问题:What is the correct way of using C++11's range-based for?)
请注意,内部基于范围的for循环内部may use iterators。
std::list<std::pair<listStr, int> >::const_iterator i;
for (std::pair<listStr, int> &elementFromOuterList: _execCmd) {
// now given that elementFromOuterList you can do whatever you need to
}