C++ 如何在C+中访问std::set two by two中的元素+;

C++ 如何在C+中访问std::set two by two中的元素+;,c++,stdvector,c++98,stdset,C++,Stdvector,C++98,Stdset,我有一个整数列表。(当前存储在std::vector中,但为了提高效率,我需要将其转换为set。但在当前版本中,我使用它如下:(我使用的是c++98而不是c++11) 这可能有效(从begin()迭代到end()-1,并使用std::next或++获取当前项目旁边的项目) 在C++11中: for (it = partialSolution.begin(); it != std::prev(partialSolution.end()); ++it) { res+=costMatrix[*

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

这可能有效(从
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]; 
}
std::set::iterator last=partialSolution.end();
--最后;
for(it=partialSolution.begin();it!=last;++it)
{
//不是最理想的,但我想让它更容易理解。。。
std::set::iterator next=it;
++其次;
res+=costMatrix[*it][*next];
}

“当前存储在
std::vector
中,但为了提高效率,我需要将其转换为
std:;set
”-这似乎不太可能提高性能,
std::set
对缓存非常不友好。在我的代码的其他地方,我正在搜索向量是否包含特定的数字。实际上,我必须更改该部分。但要更改它,我也必须更改我上面提到的部分。@bobtfish如果你希望y也有同样的行为,那么我们的
设置
作为你的
向量
,我必须假设你的
向量
已排序。因此,你可以使用来高效地查找现有元素(或者,即使你只需要知道它存在,也不需要访问它)。@zwlayer我正在尝试确定这是否是一个。问题是“我怎么能射自己的脚?”,唯一正确的答案是“不要!”你更应该听听他说的话。
vector
很有可能会比你的
set
尝试做得更好……这是c++11,OP要求c++98我认为c++11可以更好地使用
std:accumulate
,但可能不行。@jpo38你知道我如何用set来表示这个吗?
(inti=1;同样的方法,但只需执行
std::set::iterator prev=it;--prev;
,然后执行
answer+=costMatrix[partialSolution[*prev]]][partialSolution[*it]];
。循环必须以
++begin begin()
@jpo38无法理解的方式开始,如果可能,您可以将其作为编辑来编写吗?
for (it = partialSolution.begin(); it != std::prev(partialSolution.end()); ++it)
{
    res+=costMatrix[*it][*(std::next(it))]; 
}
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]; 
}