STL vector for C++ learning

What is Vector?

Ask chatgpt to see what the answer is?

ChatGPT:

C++ vectoris a dynamic array container provided by the standard library (STL). It is able to automatically resize as needed at runtime and can store elements of different types.

Using vector, you can conveniently add, remove, and access elements without having to deal with memory management manually. vectorProvides a collection of member functions and operators that allow you to perform common operations such as appending elements to the end, inserting elements at specified positions, accessing elements, and more.

To use vector, you first need to include the header file <vector>, then you can declare an vectorobject and initialize it, for example:

#include <vector>

int main() {
    // 声明一个存储整数的vector
    std::vector<int> myVector;

    // 向vector中添加元素
    myVector.push_back(10);
    myVector.push_back(20);
    myVector.push_back(30);

    // 访问vector中的元素
    int firstElement = myVector[0];
    int secondElement = myVector[1];

    // 输出vector中的元素
    for (int i = 0; i < myVector.size(); ++i) {
        std::cout << myVector[i] << " ";
    }

    return 0;
}

In the above example, we created an vectorobject for storing integers myVector, and push_backadded three integers sequentially through the function.

Then, we used the indexing operator []to access vectorthe elements in , and used a loop to output all the elements.

vectorMany other useful member functions are provided, such as size()for obtaining the number of elements, insert()for inserting elements at a specified position, erase()for deleting elements at a specified position or within a range, and so on. vectorYou can find more information about and usage in the C++ Standard Library documentation .

Fuck the gospel for real beginners.

Apply what you have learned leedcode a daily question

338. Counting Bits

Given an integer  n , for  0 <= i <= n each of  i , count  1 the number in its binary representation  , and return an  n + 1 array of  length ans as the answer.

Example 1:

Input: n = 2
 Output: [0,1,1]
 Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2:

Input: n = 5
 Output: [0,1,1,2,1,2]
 Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
	vector<int> countBits(int n) {
		int i = 1;
		vector<int> ans(n + 1);
		for (int i = 0; i <= n; i++) {
			if (i % 2 == 0)
				ans[i] = ans[i / 2];
			else
				ans[i] = ans[i / 2] + 1;
		}
		return ans;

	}
};

int main()
{

	Solution slt;
	vector<int> anss;
	int i;
	cin >> i;
	anss = slt.countBits(i);
	// 使用迭代器 iterator 访问值
	vector<int>::iterator v = anss.begin();
	while (v != anss.end()) {
		cout << "value of v = " << *v << endl;
		v++;
	}



}

Guess you like

Origin blog.csdn.net/m0_59054762/article/details/131272439