c++:unordered_map 与 string_viewes 对

c++ : unordered map with pair of string_viewes

这是我的代码片段:

    struct PairHasher {
        size_t operator()(const std::pair<std::string_view, std::string_view>& stop_stop) const {
            return hasher(stop_stop.first) + 37*hasher(stop_stop.second);
        }
        std::hash<std::string_view> hasher;
    };


BOOST_FIXTURE_TEST_CASE(unordered_map_string_view_pair_must_be_ok, TestCaseStartStopMessager)
{
    const std::vector<std::string> from_stops = {"from_0", "from_1", "from_2"};
    const std::vector<std::string> to_stops = {"to_0", "to_1", "to_2"};

    std::unordered_map<std::pair<std::string_view, std::string_view>, std::int32_t, TransportCatalogue::PairHasher> distance_between_stops;
    for ( std::size_t idx = 0; idx < from_stops.size(); ++idx) {
        std::cout << from_stops[idx] << " : " << to_stops[idx] << std::endl;
        distance_between_stops[std::pair(from_stops[idx], to_stops[idx])] = idx;
    }

    std::cout << "MAP CONTENT :" << std::endl;
    for (auto const& x : distance_between_stops)
    {
        std::cout << x.first.first << " : " << x.first.second << std::endl;
    }
}

我希望在容器内看到 3 对,但只有 1 对与输出有关:

MAP CONTENT :
from_2 : to_2

那么,又丢了两对呢?我做错了什么?

将我的评论移至答案。

这很狡猾。我在 Compiler Explorer 中注意到更改:

distance_between_stops[std::pair(from_stops[idx], to_stops[idx])] = idx;

distance_between_stops[std::pair(std::string_view{from_stops[idx]}, std::string_view{to_stops[idx]})] = idx;

修复了错误。这暗示问题在于某些隐式 string -> string_view 转换。确实是这样,只是多了一层而已。

std::pair(from_stops[idx], to_stops[idx]) 创建 std::pair<std::string, std::string>,但 distance_between_stops 需要 std::pair<std::string_view, std::string_view>。当我们将值插入映射时,这种转换通过重载 #5 here:

隐式发生
template <class U1, class U2>
constexpr pair(pair<U1, U2>&& p);
  1. Initializes first with std::forward<U1>(p.first) and second with std::forward<U2>(p.second).
  • This constructor participates in overload resolution if and only if std::is_constructible_v<first_type, U1&&> and std::is_constructible_v<second_type, U2&&> are both true.
  • This constructor is explicit if and only if std::is_convertible_v<U1&&, first_type> is false or std::is_convertible_v<U2&&, second_type> is false.

(作为参考,std::is_constructible_v<std::string_view, std::string&&>std::is_convertible_v<std::string&&, std::string_view> 都是 true,所以我们知道这个重载是可行的和隐含的。)

看到问题了吗?当我们使用映射的 operator[] 时,它必须进行隐式转换以创建具有正确类型的键。这种隐式转换构造了一对 string_view,它们正在从本地 string 对查看 临时 内存,而不是 [=38] 中的基础字符串=].换句话说,它在概念上类似于:

std::string_view foo(const std::string& s) {
    std::string temp = s + " foo";
    return temp;
}
int main() {
    std::string_view sv = foo("hello");
    std::cout << sv << "\n";
}

Clang 针对这个小示例发出警告,但不是 OP 的完整示例,这很不幸:

warning: address of stack memory associated with local variable 'temp' returned [-Wreturn-stack-address]
    return temp;
           ^~~~