std::distance 未提供“自动”创建的数组的正确值

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

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

std::find
按预期完成工作,但是
std::distance
总是返回3,我尝试了各种配置,或者
auto iterator
前面的
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++ iterator std
1个回答
0
投票

std::find
使用
==
作为比较器,因此转向需要与要查找的元素完全匹配。

您要找的是

std::find_if
:

// std::array<char const*, 3>
const auto b = std::array{"uF", "nF", "pF"}; 

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(),
    [&](char const* e) {
        return str.ends_with(e);
    }
);

debug  << "b has type: " << typeid(it).name() << '\n';
// b has type:  PKPKc

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

您可能会注意到,auto 不会在运行时推导类型。 C++ 中的所有类型,无论你是否使用

auto
,都是固定的,就像你用手写的一样。

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

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

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