c++动态数组vector

遍历

#include <vector>
void traverse(){
	vector<int> myint{1,2,3,4,5};//动态数组
    for(auto i : myint){
        cout<<i<<endl;
    }
    //正向迭代
    for (auto ib = myint.begin(), ie = myint.end(); ib!=ie; ib++) {
        cout<<*ib<<endl;
    }
    //逆向迭代
    for (auto rb = myint.rbegin(), re = myint.rend(); rb!=re; rb++) {
        cout<<*rb<<endl;
    }
    
    for (int i=0; i<20; i++) {
        myint.push_back(i);
    }
    myint.resize(6);//动态调整大小
    myint.resize(6, 90);//缓冲90
    for(int i=0; i<myint.size();i++){
        cout<<i<<endl;
    }
}

增删查改

void change(){
    vector<int> myint{1,2,3,4,5};//动态数组
    auto it = myint.begin()+3;//指针向下查找3个,也就是第4个
    cout<< *it<<endl<<"==="<<endl;
    
    //增
    myint.push_back(300);//后插入
    //myint.pushfront(200);//X 没有前插入
    myint.insert(it, 100);//某个位置插入
    int a[5]{6,7,8,9,0};
    myint.insert(it, a, a+5);//出入一个数组
    myint.insert(it, 400);//某个位置插入
    //删
    myint.erase(it);//删除1个
    myint.erase(myint.begin(),myint.end()-1);//批量删除
    //改
    myint.assign(7, 200);//重新初始化未7个200;
    //查
    for(auto i : myint){
        cout<<i<<endl;
    }
    cout<<"==="<<endl;
    for(int i=0; i<myint.size();i++){
        cout<<myint[i]<<endl;
    }
}

vector在堆上分配内存,不会栈溢出

	vector<int> mydb;
	for(int i=0;i<10000000;i++){
		mydb.push_back(i);
	}

vector内存连续

	vector<int> myint{1,2,3,4,5};//动态数组
	for(int i=0;i<5;i++){
		cout<<myint[i]<<"  	"<<&myint[i]<<endl;
	}

算法演练

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

vector<int> twoSum(vector<int>& nums, int target)
{
    vector<int> result;

    unsigned long cnt = nums.size();

    for(int i=0;i<cnt;i++)
    {
        for(int j=i+1;j<cnt;j++)
        {
            if(nums[i]+nums[j]==target)
            {
                result.push_back(i);
                result.push_back(j);
                return result;
            }
        }
    }
    return result;
}

验证:

int main(int argc, const char * argv[]) {
    vector<int> nums{1,2,4,5,6};
    vector<int> result= twoSum(nums, 9);
    int ib = result[0];
    int ie = result[1];
    cout<<"["<<ib<<","<<ie<<"]"<<endl;
    return 0;
}

版权声明:本文为zhuxincheng_1218原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。