【发布时间】:2018-07-27 14:25:29
【问题描述】:
我的问题与one略有不同。
有一个包含两个元素的 unordered_set。我想像这样“同时”操作这两个元素:
unordered_set<vector<bool>> st;
st.insert(vector<bool>(100,true));
st.insert(vector<bool>(100,false));
// vector<bool> temp_v(100,true);
// temp_v[3] = false;
// st.insert(move(temp_v));
if (st.size()!=2) return;
for (int i=0; i<100; i++)
cout << (st.begin()->at(i)) ^ (st.rbegin()->at(i)) << endl;
但是,unordered_set 没有成员函数 rbegin()。我知道我可以使用指向u_s::begin() 的迭代器并将其推进一个。有没有更“优雅”的方式来做到这一点?
--------------------------解决方案---------- ----------------------------------
受@YSC启发,一个elegant达到目的的方式是:
auto & e1 = *begin(st);
auto & e2 = *(++begin(st));
for (int i=0; i<100; i++) cout << e1[i] ^ e2[i] << endl;
这可能依赖于#include <algorithm>,与双迭代器解决方案几乎相同。
【问题讨论】:
-
std::unordered_set仅提供前向迭代器。没有办法向后迭代。考虑到unordered_set是无序的,即使是最后一个元素的概念也是值得怀疑的。有一个最后一个元素,但一个元素是最后一个这一事实并不重要。 -
看起来你使用了错误的容器,哪个元素是第一个或第二个?
-
只是这个
unordered_set<vector<int>> st;无法编译。 Life demonstration。无论如何,一组无序的向量有什么好处?你的用例是什么?对我来说,这看起来像 XY Problem。 -
我不明白您为什么要尝试从 UNORDERED 集合中提取订单。第一的?最后的?开始?结尾?这些话在这里毫无意义。
-
...您希望您的代码 sn-p 的输出是什么?