【问题标题】:str::find() function for the const char*const char* 的 str::find() 函数
【发布时间】:2021-12-09 07:36:39
【问题描述】:
const char *attribute[]  = 
{"abc","efg","hij","lmn","opq","rst","uvw","Xyz"};

想在上面的数组中找到“lmn”的布尔值和位置。

【问题讨论】:

  • 或者,如果您的编译器进行常量字符串优化并且文字 "lmn" 的所有实例都将相同(很可能),那么只需简单的 std::find(begin(attributes), end(attributes), "lmn")?或者完全停止对任何类型的字符串使用char*,而只使用std::string?

标签: c++ find std


【解决方案1】:

本示例将向您展示如何同时获取布尔值和索引。 在这里演示:https://onlinegdb.com/vHHJ9QG1M

#include <array>
#include <limits>
#include <algorithm>
#include <iostream>
#include <string_view>

// make a struct to be able to return two (readable) values from function
// I almost never use std::pair it results in hard to read code.
// where you have to check the semantics of first/second over and over again.
struct is_attribute_result_t
{
    // conversion to bool so result can be directly used in "if's" 
    constexpr operator bool() const 
    {
        return is_attribute;
    }

    bool is_attribute{false};
    std::size_t index{std::numeric_limits<std::size_t>::max()};
};


// make a std::array that is usable at compile time
// use string_view because it implements operator== for the whole string (const char* doesn't)
constexpr std::array<std::string_view,8> attributes = {"abc","efg","hij","lmn","opq","rst","uvw","xyz"};
 
// make a function that can be evaluated at compile time
// so no std::find, just use availability of (constexpr) operator== on string_view
constexpr is_attribute_result_t test_attribute(const std::string_view& attribute)
{
    is_attribute_result_t result;
    for(std::size_t n = 0; n < attributes.size(); ++n)
    {
       if(attribute == attributes[n])
       {
            result.is_attribute = true;
            result.index = n;
            return result;
       }
    }
    
    return result;
}


int main()
{
    // nice thing is you can now also check at compile time.
    static_assert(test_attribute("abc"));
    static_assert(test_attribute("abc").index == 0ul);
    static_assert(test_attribute("lmn"));
    static_assert(test_attribute("lmn").index == 3ul);
    static_assert(!test_attribute("123"));
    
    // and ofcourse still use the function at runtime too
    if ( auto result = test_attribute("lmn"))
    {
       std::cout << "lmn is an attribute, and is found at index = " << result.index << "\n";
    }

    return 0;
}

【讨论】:

  • 你可以使用std::find_if + std::distance。不幸的是后者不是 constexpr
  • 我最近有点 constexpr 的心情,所以我会保持原样;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 2018-12-20
  • 1970-01-01
相关资源
最近更新 更多