如何到达标准中的元素::在C++中设置两个乘二
How to reach elements in a std::set two by two in C++
>我有一个整数列表。目前存储在 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];
}
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如何使用 pthreads 以正确的方式设置两个线程之一的优先级
- 如何设置一个 std::vector 与另一个,其中两个是不同类的向量?
- 如何找出在两个整数的乘积中设置了多少位(等于 1)
- C++设计:如何设置共享一组变量的两个类
- 如何使 MFC Visual Studio C++ 程序在双处理器设置中使用两个 CPU
- 如何将一个类的两个单独实例设置为彼此相等的 c++
- 如何将 GMock EXPECT_CALL设置为为模拟函数调用两个不同的函数
- 如何比较两个比较两个标准::设置
- 如何在两个其他两个之间设置工具栏
- 在给定两个排序向量的情况下设置减法
- 两个默认参数都设置为给出错误/
- 将 strtok 分隔符设置为两个字符
- 将元素设置在两个尺寸 std::vector
- 通过将两个不同的文本框值相乘来设置标签的文本值
- 如何到达标准中的元素::在C++中设置两个乘二
- 设置两个结构体相等后,指针为NULL
- 如何在Visual c++中使用#pragma同时启用两个区域设置
- 我不能将两个用户定义的类声明变量设置为彼此相等?
- 在c++中使用两个宏设置变量值