【问题标题】:How to reach elements in a std::set two by two in C++如何在 C++ 中两两访问 std::set 中的元素
【发布时间】:2016-01-15 14:26:41
【问题描述】:

我有一个整数列表。(当前存储在 std::vector 中,但为了提高效率,我需要将其转换为 set。但在当前版本中,我使用它如下:(我使用的是 c+ +98 不是 c++11)

int res=0;
vector<vector<int> >costMatrix;
vector<int>partialSolution;
    for(int i =0;i<partialSolution.size()-1;i++){
        res+=costMatrix[partialSolution.get(i)][partialSolution.get(i+1)];
    }

所以,我需要对设置的数据结构做同样的事情。但我不知道如何一次从集合中获取两个元素。我可以使用下面的代码获得partialSolution.get(i),但我无法获得partialSolution.get(i+1)。有人帮我修改下面的代码吗?

 // this time set<int> partialSolution
    int res=0;
    std::set<int>::iterator it;
    for (it = partialSolution.begin(); it != partialSolution.end(); ++it)
{
    res+=costMatrix[*it][]; 
}

【问题讨论】:

  • "当前存储在std::vector,但为了提高效率,我需要将其转换为std:;set" - 这似乎不太可能提高性能,std::set 对缓存非常不友好。
  • 在我的代码的其他地方,我正在搜索我的向量是否包含特定数字。实际上我必须改变那部分。但是要改变它,我也必须改变我上面提到的部分。 @BoBTFish
  • 如果您希望 set 的行为与您的 vector 相同,我必须假设您的 vector 已排序。因此,您可以使用std::lower_bound 有效地查找现有元素(如果您只需要知道它存在而不需要访问它,甚至可以使用std::binary_search)。
  • @zwlayer 我正在尝试确定这是否是XY Problem。当问题是“我怎样才能射中自己的脚?”时,唯一正确的答案是“不要!”
  • 你应该听听他在说什么。 vector 很有可能会胜过您的 set 尝试...

标签: c++ stdvector c++98 stdset


【解决方案1】:

这可以工作(从begin() 迭代到end()-1 并使用std::next++ 来获取当前项目旁边的项目)。

在 C++11 中:

for (it = partialSolution.begin(); it != std::prev(partialSolution.end()); ++it)
{
    res+=costMatrix[*it][*(std::next(it))]; 
}

在 C++98 中:

std::set<int>::iterator last = partialSolution.end();
--last;
for (it = partialSolution.begin(); it != last; ++it)
{
    // not optimal but I'm trying to make it easy to understand...
    std::set<int>::iterator next = it;
    ++next;
    res+=costMatrix[*it][*next]; 
}

【讨论】:

  • 是c++11,OP要求c++98
  • 我认为 C++11 使用 std:accumulate 可能会更好,但也许不会。
  • @jpo38 你知道我怎么能用一组来表示这个? for(int i=1;i&lt;partialSolution.size()-1;i++){ answer+=costMatrix[partialSolution[i-1]][partialSolution[i]]; }
  • 以同样的方式,但只需执行std::set&lt;int&gt;::iterator prev = it; --prev;,然后执行answer+=costMatrix[partialSolution[*prev]][partialSolution[*it]];。循环必须以 ++begin() 开头。
  • @jpo38 想不通,如果可能的话你能把它写成编辑吗?
猜你喜欢
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 2011-11-03
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 2010-12-14
相关资源
最近更新 更多