Sorting 使用std::nexting_find和自定义谓词在向量上迭代
在从左到右以2分隔的向量中搜索和打印元素对时遇到问题。我需要收集这对 我操作的示例数据是:Sorting 使用std::nexting_find和自定义谓词在向量上迭代,sorting,c++11,stl,stl-algorithm,Sorting,C++11,Stl,Stl Algorithm,在从左到右以2分隔的向量中搜索和打印元素对时遇到问题。我需要收集这对 我操作的示例数据是: std::vector myvector={1,3,3,5,7,9,13,10,12} 假设std::innect_find谓词是: static const auto gAdjacentPred = []( const int& lhs, const int& rhs) { std::cout << "(" << lhs <
std::vector myvector={1,3,3,5,7,9,13,10,12}代码>
假设std::innect_find谓词是:
static const auto gAdjacentPred = [](
const int& lhs, const int& rhs) {
std::cout
<< "(" << lhs << ":" << rhs << ")?"
<< std::string((rhs == lhs+2)? "true" : "false")
<< std::endl;
return (rhs == lhs+2);
};
理想思想(我不知道怎么做),我想合并满足输入数据中间谓词的值…3, 5, 7, 9 ... 作为单一结果,
{3,9}
问题是我真的不明白如何正确地循环集合。我确实看到std::next(iter)是一个技巧,我可以使用它来提前查看满足lambda的最右边的值,但是这有时会指向集合的末尾
我希望我在数据上循环的方式会在谓词在集合上迭代时显示对谓词的多次调用,因为它只调用谓词函数一次(当我分配给形容词时,
。同样,在结果中,我看到对13和10似乎满足谓词。有人能解释一下这是怎么回事吗,因为我需要从左到右找到不同值的对-在我的例子中是2(左侧小于右侧)(我正在搜索从左到右递增的值)
问题是最后一对也被考虑在内
static const auto gAdjacentPred = [](
const int& lhs, const int& rhs) {
std::cout
<< "(" << lhs << ":" << rhs << ")?"
<< std::string((rhs == lhs+2)? "true" : "false")
<< std::endl;
return (rhs == lhs+2);
};
std::vector<int> myvector = { 1, 3, 3, 5, 7, 9, 13, 10, 12 };
auto adjIter = std::adjacent_find (
myvector.begin(), myvector.end(),
gAdjacentPred);
while (adjIter != myvector.cend()) {
auto second = std::next(adjIter);
// print both sides
if (second != myvector.cend()) {
std::cout << "{" << *adjIter << "," << *second << "}" << std::endl;
adjIter +=2;
} else {
adjIter++;
}
}
static const auto gAdjacentPred=[](
常量内部和左侧、常量内部和右侧){
标准::cout
嗯,您只调用一次std::nextendent\u find
。如果您既不调用谓词也不将其传递给任何函数,那么在找到第一对谓词后,您为什么会期望对谓词进行更多调用?您应该在循环中调用std::nextendent\u find
。@IgorTandetnik-谢谢-我刚刚弄明白了,正在编辑我的问题(在回答任何问题之前,我要把重点放在我原始问题的第二部分,即如何合并并排的所有对,以便将输入数据…3,5,7,9…转换为单个结果{3,9}。我发现如何在这里重复调用迭代器:。我真的在想
(1:3)?true
{1,3}
{3,5}
{7,9}
{13,10}
static const auto gAdjacentPred = [](
const int& lhs, const int& rhs) {
std::cout
<< "(" << lhs << ":" << rhs << ")?"
<< std::string((rhs == lhs+2)? "true" : "false")
<< std::endl;
return (rhs == lhs+2);
};
std::vector<int> myvector = { 1, 3, 3, 5, 7, 9, 13, 10, 12 };
auto adjIter = std::adjacent_find (
myvector.begin(), myvector.end(),
gAdjacentPred);
while (adjIter != myvector.cend()) {
auto second = std::next(adjIter);
// print both sides
if (second != myvector.cend()) {
std::cout << "{" << *adjIter << "," << *second << "}" << std::endl;
adjIter +=2;
} else {
adjIter++;
}
}