- 一、Vector容器
- 二、结构化绑定
一、Vector容器
Vector容器是一个长度可变的数组(称为向量)。
#pragma once
#include
#include
#include
#define PRINT(x) std::cout<<#x<<":"<<x<<std::endl;
template<typename T>
std::ostream& operator<<(std::ostream& s, const std::vector<T>& v)
{
s.put('[');
char comma[3] = { ','' ','}'; for(
const auto& :) e << v<<
{
s ; comma [ e0
comma]=',' ; }return
<<
']' s ; }int
main
( )//用C++11的列表初始化 创建vector对象words1::
{
<
std::vector"Hello"std,string> words1{ "World","Welcome","To","C!"}; PRINT(
);words1//删除words1最后一个元素.
erase
words1(.endwords1()-1 ) ;PRINT(
);words1//在words1尾部追加元素.
push_back
words1("C++!");PRINT(
);words1//用迭代器拷贝words1的内容以创建words2::
words2
std(vector .beginwords1()+2 , .end words1());PRINT(
);words2//在words2中插入元素.
insert
words2(.beginwords2(),"Hello!") ;PRINT(
);words2//用拷贝构造创建words3::
words3
std(vector );words2PRINT(
);words3//用[]修改words3的元素[
3
words3]="C Plus Plus" ; PRINT(
);words3//创建words4,初始化为多个相同的字串::
<
std::vectorwords4std(string> 4,"C++!") ;PRINT(
);words4//words3与words4交换.
swap
words3();words4PRINT(
);words3PRINT(
);words4::.
stdgetcin();}#
include
结果如上图所示。
结构化绑定可以理解为里面的元素顺序对应赋值。
#include
//定义结构体,包含double和int成员struct
S
//calss S{ public: double
{
1.0
} d1{ ; int32
} i1{ ; };
:int
class C
{
public1
} i2{ ; char[
3 c]'a',{ 'b','}';} ;int
main(
) ::1,
{
std2array a{ ,3};:: <int
std,array211, 12> b{ };auto &[
,, ]e1= e2; e3[ 0 a]
a=10; :: <<<<
std" "cout << e1 << " " << e2 << :: ; e3 //定义结构体和类对象 std;endl;
//绑定结构体变量
S sauto
C c[
,
] }d1; i1//以引用形式绑定类对象成员 {sauto&
[
,] }i2; c2//输出绑定的成员 {c::<<
"s.d="
std<<cout << " s.i1=" << d1 << :: ; i1 :: std<<endl"c.i2= "
std<<cout << " c.c[3]= " << i2 << :: ; c2 :: std.endlget
std(cin);return0;
}
结果如上图所示
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)