我有一个存储所有目录及其相应文件的功能。
我在显示 VALUE map 时遇到问题。我已经调试并观察到相应的值已正确存储,但我无法显示它。由于 map 的值部分本身就是一个 pathiterator 列表。每当我在不同的目录中获得相同的文件名时,我都会将引用或路径迭代器存储在对应于相同键(文件名)的映射中。请仔细查看。
void search()
{
using path_1 = std::string;
using paths_1 = std::set<path_1>;
using pathiter = paths_1::iterator;
using listofiter = std::list<pathiter>;
using file = std::string;
using store = std::map<file, listofiter>;
using store_iter = store::iterator;
paths_1 pp;
pathiter oo;
store s6;
for (recursive_directory_iterator i("."), end; i != end; ++i)
{
pp.insert(i->path().parent_path());
oo = pp.find(i->path().parent_path());
if (!is_directory(i->path()))
{
s6[i->path().filename()].push_back(oo);
}
}
store_iter d;
for ( d = s6.begin(); d != s6.end(); d++)
{
cout << "Key: " << d->first << " Value: "<<d->second;
// ^^not able
//to print it!!
}
}
我添加了我在调试时截取的屏幕截图。如果同一文件出现在不同的位置,d->second {size}
将大于 1。
我想到了应用循环:我就是这样做的。我想我搞砸了。
for ( d = s6.begin(); d != s6.end(); d++)
{
cout << "Key: " << d->first << " Value: ";
for (int i = 0; i < d->second.size; i++)
{
cout << d->second[i];
// ^^Error at this place
}
}
错误:在循环中使用循环
最佳答案
<< d->second
不起作用,因为那是一个集合。
您已经知道一种显示集合的方法,使用 for( ; ; )
环形。由于容器内有容器,因此您需要在 for 循环内使用 for 循环来打印所有元素。
作为奖励,您可以通过以下方式编写更紧凑的循环:
for (auto&& element : container) { ...
不需要迭代器、开始和结束调用。这一切都为你处理了。循环体对容器中的每个元素执行一次。相同的限制适用:不要尝试在循环内添加或删除元素。
[编辑]
您添加了一种新的第三种 for 循环。由于某种原因,您现在尝试使用 for(int i = 0; i != container.size; ++i)
迭代一个容器。为什么?您已经知道一种行之有效的方法,而我只是向您展示了另一种行之有效的方法。
顺便说一句,它不起作用的原因是 [i]
需要 operator[]
,这在大多数容器中都不存在。 begin/end
存在于所有容器中。
关于c++ - 如何在 MAP STL : C++ 中显示 LIST 中包含的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295377/