C++11中的stoi和stod怎么使用
导读:本文共19432.5字符,通常情况下阅读需要65分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要:接下来,请跟着小编一起来学习吧!C++11的stoi & stod#include<iostream>include<string>usingnamespacestd;intmain(){stringstr="123";inta=stoi(str);//如果遇到非法输入,stoi会自动截取最前面的数字,知道遇到不是数字为止//所以说... ...
目录
(为您整理了一些要点),点击可以直达。接下来,请跟着小编一起来学习吧!
}
c++11新特性集合
#C++11若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!Seealso:
std::move
,std::forward
,forwardingreferences
.Templatetypeparameterdeductionwithlvaluesandrvalues:
Seealso:
std::move
,std::forward
,rvaluereferences
.The
...
syntaxcreatesa_parameterpack_orexpandsone.Atemplate_parameterpack_isatemplateparameterthatacceptszeroormoretemplatearguments(non-types,types,ortemplates).Atemplatewithatleastoneparameterpackiscalledavariadictemplate.Aninterestinguseforthisiscreatingan_initializerlist_froma_parameterpack_inordertoiterateovervariadicfunctionarguments.
Alightweightarray-likecontainerofelementscreatedusinga"bracedlist"syntax.Forexample,
{1,2,3}
createsasequencesofintegers,thathastypestd::initializer_list<int>
.Usefulasareplacementtopassingavectorofobjectstoafunction.Assertionsthatareevaluatedatcompile-time.
auto
-typedvariablesarededucedbythecompileraccordingtothetypeoftheirinitializer.Extremelyusefulforreadability,especiallyforcomplicatedtypes:
Functionscanalsodeducethereturntypeusing
auto
.InC++11,areturntypemustbespecifiedeitherexplicitly,orusingdecltype
likeso:Thetrailingreturntypeintheaboveexampleisthedeclaredtype(seesectionon
decltype
)oftheexpressionx+y
.Forexample,ifx
isanintegerandy
isadouble,decltype(x+y)
isadouble.Therefore,theabovefunctionwilldeducethetypedependingonwhattypetheexpressionx+y
yields.Noticethatthetrailingreturntypehasaccesstoitsparameters,andthis
whenappropriate.Bydefault,value-capturescannotbemodifiedinsidethelambdabecausethecompiler-generatedmethodismarkedas
const
.Themutable
keywordallowsmodifyingcapturedvariables.Thekeywordisplacedaftertheparameter-list(whichmustbepresentevenifitisempty).
decltype
isanoperatorwhichreturnsthe_declaredtype_ofanexpressionpassedtoit.cv-qualifiersandreferencesaremaintainediftheyarepartoftheexpression.Examplesofdecltype
:Seealso:
decltype(auto)
(C++14).Semanticallysimilartousinga
typedef
however,typealiaseswithusing
areeasiertoreadandarecompatiblewithtemplates.C++11introducesanewnullpointertypedesignedtoreplaceC's
NULL
macro.nullptr
itselfisoftypestd::nullptr_t
andcanbeimplicitlyconvertedintopointertypes,andunlikeNULL
,notconvertibletointegraltypesexceptbool
.Type-safeenumsthatsolveavarietyofproblemswithC-styleenumsincluding:implicitconversions,inabilitytospecifytheunderlyingtype,scopepollution.
Attributesprovideauniversalsyntaxover
__attribute__(...)
,__declspec
,etc.Constantexpressionsareexpressionsevaluatedbythecompileratcompile-time.Onlynon-complexcomputationscanbecarriedoutinaconstantexpression.Usethe
constexpr
specifiertoindicatethevariable,function,etc.isaconstantexpression.
constexpr
valuesarethosethatthecompilercanevaluateatcompile-time:Constantexpressionswithclasses:
Constructorscannowcallotherconstructorsinthesameclassusinganinitializerlist.
User-definedliteralsallowyoutoextendthelanguageandaddyourownsyntax.Tocreatealiteral,definea
Toperator""X(...){...}
functionthatreturnsatypeT
,withanameX
.Notethatthenameofthisfunctiondefinesthenameoftheliteral.Anyliteralnamesnotstartingwithanunderscorearereservedandwon'tbeinvoked.Therearerulesonwhatparametersauser-definedliteralfunctionshouldaccept,accordingtowhattypetheliteraliscalledon.ConvertingCelsiustoFahrenheit:
Stringtointegerconversion:
Specifiesthatavirtualfunctionoverridesanothervirtualfunction.Ifthevirtualfunctiondoesnotoverrideaparent'svirtualfunction,throwsacompilererror.
Specifiesthatavirtualfunctioncannotbeoverriddeninaderivedclassorthataclasscannotbeinheritedfrom.
Classcannotbeinheritedfrom.
Amoreelegant,efficientwaytoprovideadefaultimplementationofafunction,suchasaconstructor.
Withinheritance:
Amoreelegant,efficientwaytoprovideadeletedimplementationofafunction.Usefulforpreventingcopiesonobjects.
Syntacticsugarforiteratingoveracontainer'selements.
Notethedifferencewhenusing
int
asopposedtoint&
:Thecopyconstructorandcopyassignmentoperatorarecalledwhencopiesaremade,andwithC++11'sintroductionofmovesemantics,thereisnowamoveconstructorandmoveassignmentoperatorformoves.
Convertingconstructorswillconvertvaluesofbracedlistsyntaxintoconstructorarguments.
Notethatthebracedlistsyntaxdoesnotallownarrowing:
Notethatifaconstructoracceptsa
std::initializer_list
,itwillbecalledinstead:Conversionfunctionscannowbemadeexplicitusingthe
explicit
specifier.Allmembersofaninlinenamespacearetreatedasiftheywerepartofitsparentnamespace,allowingspecializationoffunctionsandeasingtheprocessofversioning.Thisisatransitiveproperty,ifAcontainsB,whichinturncontainsCandbothBandCareinlinenamespaces,C'smemberscanbeusedasiftheywereonA.
Allowsnon-staticdatamemberstobeinitializedwheretheyaredeclared,potentiallycleaningupconstructorsofdefaultinitializations.
C++11isnowabletoinferwhenaseriesofrightanglebracketsisusedasanoperatororasaclosingstatementoftypedef,withouthavingtoaddwhitespace.
Memberfunctionscannowbequalifieddependingonwhether
*this
isanlvalueorrvaluereference.C++11allowsfunctionsandlambdasanalternativesyntaxforspecifyingtheirreturntypes.
Thisfeatureisespeciallyusefulwhencertainreturntypescannotberesolved:
InC++14,
decltype(auto)
canbeusedinstead.The
noexcept
specifierspecifieswhetherafunctioncouldthrowexceptions.Itisanimprovedversionofthrow()
.Non-throwingfunctionsarepermittedtocallpotentially-throwingfunctions.Wheneveranexceptionisthrownandthesearchforahandlerencounterstheoutermostblockofanon-throwingfunction,thefunctionstd::terminateiscalled.
Transferring
std::unique_ptr
s:Anexampleofafunction
wrapper
whichjustforwardsotherA
objectstoanewA
object'scopyormoveconstructor:Seealso:
forwardingreferences
,rvaluereferences
.The
std::thread
libraryprovidesastandardwaytocontrolthreads,suchasspawningandkillingthem.Intheexamplebelow,multiplethreadsarespawnedtododifferentcalculationsandthentheprogramwaitsforallofthemtofinish.Convertsanumericargumenttoa
std::string
.Typetraitsdefinesacompile-timetemplate-basedinterfacetoqueryormodifythepropertiesoftypes.
A
std::shared_ptr
isasmartpointerthatmanagesaresourcethatissharedacrossmultipleowners.Asharedpointerholdsa_controlblock_whichhasafewcomponentssuchasthemanagedobjectandareferencecounter.Allcontrolblockaccessisthread-safe,however,manipulatingthemanagedobjectitselfisnotthread-safe.Thechronolibrarycontainsasetofutilityfunctionsandtypesthatdealwithdurations,clocks,andtimepoints.Oneusecaseofthislibraryisbenchmarkingcode:
Tuplesareafixed-sizecollectionofheterogeneousvalues.Accesstheelementsofa
std::tuple
byunpackingusingstd::tie
,orusingstd::get
.Createsatupleoflvaluereferences.Usefulforunpacking
std::pair
andstd::tuple
objects.Usestd::ignore
asaplaceholderforignoredvalues.InC++17,structuredbindingsshouldbeusedinstead.
std::array
isacontainerbuiltontopofaC-stylearray.Supportscommoncontaineroperationssuchassorting.Thecompilerisfreetocall
newT{}
,thenfunction_that_throws()
,andsoon...SincewehaveallocateddataontheheapinthefirstconstructionofaT
,wehaveintroducedaleakhere.Withstd::make_shared
,wearegivenexception-safety:
std::ref(val)
isusedtocreateobjectoftypestd::reference_wrapper
thatholdsreferenceofval.Usedincaseswhenusualreferencepassingusing&
doesnotcompileor&
isdroppedduetotypededuction.std::cref
issimilarbutcreatedreferencewrapperholdsaconstreferencetoval.
std::begin
andstd::end
freefunctionswereaddedtoreturnbeginandenditeratorsofacontainergenerically.Thesefunctionsalsoworkwithrawarrayswhichdonothavebeginandendmemberfunctions.AnthonyCalandra
See:https://github.com/AnthonyCalandra/modern-cpp-features/graphs/contributors
MIT
C++11中的stoi和stod怎么使用的详细内容,希望对您有所帮助,信息来源于网络。