如何到达标准中的元素::在C++中设置两个乘二

How to reach elements in a std::set two by two in C++

本文关键字:两个 设置 标准 元素 C++      更新时间:2023-10-16

>我有一个整数列表。目前存储在 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][]; 
}
这可以

工作(从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]; 
}