// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
#include "string"
#include "vector"
#include<algorithm>
using namespace std;
int main()
{
std::vector<int> vec;
vec.assign(7, 100); // 7个元素,每个都是100
for (auto i : vec){
cout << i << ",";
}
cout << endl;
/////////////////////////////////////////////////////
vec.clear();
for (auto i = 0; i < 7; ++i){//1,2,3,4,5,6,7
// vec.at(i) = i+1;
vec.push_back(i+1);
}
cout << "--------------------" << endl;
/////////////////////////////////////////////////////
for (auto i : vec){
cout << i << ",";//输出: 1,2,3,4,5,6,7
}
cout << endl;
cout << "Front: " << vec.front() << endl;//1
cout << "Back: " << vec.back() << endl;//7
/////////////////////////////////////////////////////
for (auto it = vec.cbegin(); it != vec.cend(); ++it)
cout << *it << ",";//输出: 1,2,3,4,5,6,7
cout << endl;
cout <<"Size: "<< vec.size()<<endl;//7
/////////////////////////////////////////////////////
for (size_t i = 0; i < vec.size(); ++i){
cout << vec[i] << ",";//输出: 1,2,3,4,5,6,7
}
cout << endl;
//
vec.insert(vec.begin()+1, 100);
for (auto i : vec){
cout << i << ",";//输出: 1,100,2,3,4,5,6,7
}
cout << endl;
vec.erase(vec.begin() + 1);//执行后: 1,2,3,4,5,6,7
int i = 0, j =2;
vec.erase(vec.begin() + i, vec.begin() + j);// 删除区间[i, j - 1]; 区间从0开始 //执行后: 3,4,5,6,7
sort(vec.begin(), vec.end(), [](int a,int b){//& = 从大到小排列
return a > b;
});//执行后: 7,6,5,4,3
vec.pop_back();//执行后: 7,6,5,4
if (vec.empty()){
}
for (auto i : vec){
cout << i << ",";//输出: 7,6,5,4
}
cout << endl;
reverse(vec.begin(), vec.end());//元素翻转
for (auto i : vec){
cout << i << ",";//输出: 4,5,6,7
}
cout << endl;
while (1);
return 0;
}
C++ Vector
最新推荐文章于 2024-02-09 16:12:47 发布