# STLPractice

## vector

### Initialization

```cpp
// create empty vector 
vector<int> vect; 

// create a vector with n size & all value is 10
vector<int> vect(n, 10); 

// initialization list
vector<int> vect{ 10, 20, 30 }; 

// use list
int arr[] = { 10, 20, 30 }; 
int n = sizeof(arr) / sizeof(arr[0]); 
vector<int> vect(arr, arr + n); 

vector<int> vect1{ 10, 20, 30 }; 
vector<int> vect2(vect1.begin(), vect1.end());
```

## 通用

### 容器的遍历

```cpp
$ cat 08.cpp 
#include <iostream>
#include <vector>

using namespace std;

int main() {

       // positive traversal 
    vector<int> v{1, 2, 3, 4};
    for (auto i : v) {
        cout << i << endl;
    }

    cout << "----" << endl;

    for (auto iter=v.begin(); iter != v.end(); ++iter) {
        cout << *iter << endl;
    }

    cout << "----" << endl;

    // reverse traversal
    for (auto iter=v.rbegin(); iter != v.rend(); ++iter) {
        cout << *iter << endl;
    }
    return 0;
}
$ g++ 08.cpp -std=c++11 && ./a.out 
1
2
3
4
----
1
2
3
4
----
4
3
2
1
```

### swap elements

```cpp
// swap based on the objects contents:
std::swap(v[0],v[1]);

// swap based on the underlying iterator:
std::iter_swap(v.begin(),v.begin()+1);
```

* [参考](https://stackoverflow.com/questions/6224830/c-trying-to-swap-values-in-a-vector)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://note.wii.pub/coding/c++/notes/stl/stlpractice.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
