Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::basic_string<CharT,Traits,Allocator>::at

      From cppreference.com
      <cpp‎ |string‎ |basic string
       
       
       
      std::basic_string
       
      CharT& at( size_type pos);
      (1)(constexpr since C++20)
      const CharT& at( size_type pos)const;
      (2)(constexpr since C++20)

      Returns a reference to the character at specified locationpos. Bounds checking is performed, exception of typestd::out_of_range will be thrown on invalid access.

      Contents

      [edit]Parameters

      pos - position of the character to return

      [edit]Return value

      Reference to the requested character.

      [edit]Exceptions

      Throwsstd::out_of_range ifpos>= size().

      If an exception is thrown for any reason, these functions have no effect (strong exception safety guarantee).

      [edit]Complexity

      Constant.

      [edit]Example

      Run this code
      #include <iostream>#include <stdexcept>#include <string> int main(){std::string s("message");// for capacity     s="abc";    s.at(2)='x';// OKstd::cout<< s<<'\n'; std::cout<<"string size = "<< s.size()<<'\n';std::cout<<"string capacity = "<< s.capacity()<<'\n'; try{// This will throw since the requested offset is greater than the current size.        s.at(3)='x';}catch(std::out_of_rangeconst& exc){std::cout<< exc.what()<<'\n';}}

      Possible output:

      abxstring size = 3string capacity = 7basic_string::at

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 847C++98there was no exception safety guaranteeadded strong exception safety guarantee
      LWG 2207C++98the behavior was undefined ifpos>= size() istruealways throws an exception in this case

      [edit]See also

      accesses the specified character
      (public member function)[edit]
      accesses the specified character with bounds checking
      (public member function ofstd::basic_string_view<CharT,Traits>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/at&oldid=178320"

      [8]ページ先頭

      ©2009-2025 Movatter.jp