C++ “auto iter=first”这句话怎么了

C++ “auto iter=first”这句话怎么了,c++,iterator,constants,auto,C++,Iterator,Constants,Auto,这句话发生了什么变化: auto iter = first; 众所周知,为什么iter++能够很好地工作,首先是const& 为什么?这就是使用auto时类型推断的工作原理,在本例中,您获得的是first的副本,该副本的类型为iteratorT 您可以改为使用: 常量iterator&iter=first const auto&iter=第一个或仅自动& decltypefirst iter=第一 decltypeauto iter=第一个 当然,如果你想让国际热核实验堆成为常数参考的话,所有

这句话发生了什么变化:

auto iter = first;
众所周知,为什么iter++能够很好地工作,首先是const&


为什么?

这就是使用auto时类型推断的工作原理,在本例中,您获得的是first的副本,该副本的类型为iteratorT

您可以改为使用:

常量iterator&iter=first const auto&iter=第一个或仅自动& decltypefirst iter=第一 decltypeauto iter=第一个 当然,如果你想让国际热核实验堆成为常数参考的话,所有这些都可以

感谢@songyuanyao和@LogicStuff在评论中提出的建议

另请考虑以下以更清晰的方式再现问题的示例:

#include <type_traits>

int main() {
    int i = 42;
    const int & j = i;
    auto k = j;

    static_assert(std::is_same<decltype(k), int>::value, "!");
    static_assert(not std::is_same<decltype(k), const int &>::value, "!");
}

这就是使用auto时类型推断的工作原理,在本例中,您将获得first的一个副本,该副本的类型为iteratorT

您可以改为使用:

常量iterator&iter=first const auto&iter=第一个或仅自动& decltypefirst iter=第一 decltypeauto iter=第一个 当然,如果你想让国际热核实验堆成为常数参考的话,所有这些都可以

感谢@songyuanyao和@LogicStuff在评论中提出的建议

另请考虑以下以更清晰的方式再现问题的示例:

#include <type_traits>

int main() {
    int i = 42;
    const int & j = i;
    auto k = j;

    static_assert(std::is_same<decltype(k), int>::value, "!");
    static_assert(not std::is_same<decltype(k), const int &>::value, "!");
}

类型推断:您得到的是first的非常量副本。如果我不想使用auto,我该怎么办,谢谢您使用const Iterator&或const auto&如果您希望它成为常量引用。decltypefirst iter=first;,现在您得到一个常量&1。或decltypeauto。在那里,保存了一封信。类型推断:您得到的是first的非常量副本。如果我不想使用auto,我该怎么办,谢谢您使用const Iterator&或const auto&如果您希望它成为常量引用。decltypefirst iter=first;,现在您得到一个常量&1。或decltypeauto。“如果iter是一个常数参考,那么iter++如何能很好地工作,@z_chong,这就是为什么我说的——当然,如果你想让iter成为常数参考,所有这些都是。看起来这就是你的问题意图,当然,除了它会被代码破坏这一事实。如果iter是一个常量引用,那么iter++如何能够很好地工作,@z_chong,这就是为什么我说的——当然,如果你想让iter成为常量引用,所有这些都是。看起来这是你的本意,当然,除了这会破坏代码这一事实。