std::distance 在给定 std::find 返回的迭代器时提供超过结束索引

问题描述 投票:0回答:1

这是我目前正在处理的一段豁免代码。

std::find
似乎按预期完成了工作,但是
std::distance
总是返回3,我尝试了各种配置,或者
it
前面的
std::find
有问题。 我希望根据字符串的结束方式获得正确的数组索引。

it
打印地址。

const auto b = {"uF", "nF", "pF"}; 

std::string str("1.0uF");  // test string.   
//std::string str("1.0nF");  // test string.
//std::string str("1.0pF");  // test string.

auto it = std::find(b.begin(), b.end(), str);
debug  << "b has type: " << typeid(it).name() << '\n';
// b has type:  PKPKc
debug << "index: " << std::distance(b.begin(), it) <<'\n'; //*(*it) << '\n';
c++ c++11 iterator std
1个回答
2
投票

std::find()
使用
operator==
作为比较器,因此字符串需要与要查找的元素完全匹配。

您要找的是

std::find_if()
,例如:

auto ends_with(std::string const& str, std::string const& suffix) -> bool {
    if (str.length() < suffix.length()) {
        return false;
    }

    return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
}


auto main() -> int {
    using namespace std::literals; // for the 's' suffix

    const auto b = std::array<std::string, 3>{"uF"s, "nF"s, "pF"s}; 

    std::string str("1.0uF");  // test string.   
    //std::string str("1.0nF");  // test string.
    //std::string str("1.0pF");  // test string.

    // always std::string::iterator
    auto it = std::find_if(
        b.begin(), b.end(),
        [&](std::string const& e) {
            return ends_with(str, e);
        }
    );

    if (it != b.end()) {
        // found    
        debug << "index: " << std::distance(b.begin(), it) <<'\n'; //*(*it) << '\n';
    } else {
        // not found, distance is one past the end
    }
}

您可能会注意到,

auto
不会在运行时推导类型。 C++中的所有类型,无论你是否使用
auto
,都是固定的,就像你手写的一样。您只需编写适合您需求的正确逻辑即可。

只有数组可能会令人困惑,因为它默认推导

std::initializer_list
。使用
std::array
可以解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.