一、Vector容器
Vector容器是一个长度可变的数组(称为向量)。
#pragma once
#include<vector>
#include<iostream>
#include<string>
#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] = { '\0',' ','\0' };
for (const auto& e : v)
{
s << comma << e;
comma[0] = ',';
}
return s << ']';
}
int main()
{
//用C++11的列表初始化 创建vector对象words1
std::vector<std::string> words1{ "Hello","World","Welcome","To","C!" };
PRINT(words1);
//删除words1最后一个元素
words1.erase(words1.end() - 1);
PRINT(words1);
//在words1尾部追加元素
words1.push_back("C++!");
PRINT(words1);
//用迭代器拷贝words1的内容以创建words2
std::vector words2(words1.begin() + 2, words1.end());
PRINT(words2);
//在words2中插入元素
words2.insert(words2.begin(), "Hello!");
PRINT(words2);
//用拷贝构造创建words3
std::vector words3(words2);
PRINT(words3);
//用[]修改words3的元素
words3[3] = "C Plus Plus";
PRINT(words3);
//创建words4,初始化为多个相同的字串
std::vector<std::string> words4(4, "C++!");
PRINT(words4);
//words3与words4交换
words3.swap(words4);
PRINT(words3);
PRINT(words4);
std::cin.get();
}
结果如上图所示。
二、结构化绑定
结构化绑定可以理解为里面的元素顺序对应赋值。
#include<iostream>
#include<array>
//定义结构体,包含double和int成员
struct S
{
//calss S{ public:
double d1{ 1.0 };
int i1{ 32 };
};
class C
{
public:
int i2{ 1 };
char c[3]{ 'a','b','\0' };
};
int main()
{
std::array a{ 1,2,3 };
std::array<int, 2> b{ 11,12 };
auto& [e1, e2, e3] = a;
a[0] = 10;
std::cout << e1 << " " << e2 << " " << e3 << std::endl;
//定义结构体和类对象
S s;
C c;
//绑定结构体变量
auto [d1, i1] {s};
//以引用形式绑定类对象成员
auto& [i2, c2] {c};
//输出绑定的成员
std::cout << "s.d=" << d1 << " s.i1=" << i1 << std::endl;
std::cout << "c.i2= " << i2 << " c.c[3]= " << c2 << std::endl;
std::cin.get();
return 0;
}
结果如上图所示