Error with std::find

Error with std::find

本文关键字:find std with Error      更新时间:2023-10-16

所以,我基本上有这段代码:

#include <algorithm>
using std::vector;
int WpMaxSAT::findInClause(int clause, int var, ClauseType type)
{
    switch (type) {
    case SOFT:
        int val = std::find(softClauses.at(clause).begin(),
                            softClauses.at(clause).end(), var);
        break;
    case HARD:
        break;
    }
}

其中softClauses在报头中定义为:

std::vector<std::vector<int>> softClauses;

这给了我这个错误:

wpmaxsat.cpp: In member function ‘int WpMaxSAT::findInClause(int, int, WpMaxSAT::ClauseType)’:
wpmaxsat.cpp:84:66: error: cannot convert ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ to ‘int’ in initialization
                             softClauses.at(clause).end(), var);

只是要注意的是,我正在与一位朋友并行工作,所以构造函数还没有定义(他正在处理它)。但我认为问题不在于初始化。

我以为这是#include<algorithm>行的一个错误,但看起来不是。

std::find返回迭代器,而不是值。您可以阅读编译器抱怨的内容,并自行解决。

这就是正确编写代码的方式:

auto it = std::find(softClauses.at(clause).begin(),
                    softClauses.at(clause).end(), var);
if (it != softClauses.at(clause).end()) {
    int val = *it;
}

如果您只想知道值var是否存在于vector中,则可以使用std::count。它不返回迭代器,而是返回某种类型的InputIterator::difference_type,即:

有符号积分型

我会将其视为size_t,就像它通常用于STL容器一样。std::count的使用很简单:

auto count = std::count(softClauses.at(clause).begin(),
                        softClauses.at(clause).end(), var);
if (count) {
    // value exists here
}