c++ vector :
时间: 2023-10-25 08:07:34 浏览: 41
C++中的vector是一种动态数组,可以存储相同类型的元素。它提供了很多有用的方法来操作和管理数组,如添加、删除、修改元素,以及获取元素的数量等。
在引用中提到的assign函数是vector的一个成员函数,用于将区间中的元素赋值给vector或者将n个值为x的元素赋值给vector,同时会清除原有的内容。
示例代码中的main函数展示了如何使用assign函数来赋值一个vector。首先,我们创建了一个名为v1的vector并初始化它的元素为1、2、3。然后,我们使用assign函数将v1中的所有元素替换为4个值为5的元素。接下来,我们创建了一个名为v2的空vector,并使用assign函数将v1中的元素赋值给v2。
最后,我们遍历v1和v2,分别输出它们的元素。
相关问题
c++ std::vector
std::vector is a container in C++ STL (Standard Template Library) that is used to store a dynamic array of elements. It is similar to an array, but it can automatically resize itself when new elements are added or removed. The elements in a std::vector are stored in contiguous memory locations, making it easy to access them using iterators or indices.
The syntax for declaring a std::vector is:
std::vector<DataType> vectorName;
Where DataType is the type of elements that are going to be stored in the vector and vectorName is the name of the vector.
Some of the commonly used functions of std::vector are:
- push_back(): Adds an element to the end of the vector
- pop_back(): Removes the last element from the vector
- size(): Returns the number of elements in the vector
- empty(): Returns true if the vector is empty, false otherwise
- clear(): Removes all the elements from the vector
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
for (int i = 0; i < myVector.size(); i++) {
std::cout << myVector[i] << " ";
}
std::cout << std::endl;
myVector.pop_back();
for (auto it = myVector.begin(); it != myVector.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
myVector.clear();
std::cout << "Vector size after clear(): " << myVector.size() << std::endl;
return 0;
}
Output:
10 20 30
10 20
Vector size after clear(): 0
c++ std::vector 排序
C++中的std::vector是一个动态数组容器,可以存储任意类型的元素。要对std::vector进行排序,可以使用std::sort函数,该函数位于<algorithm>头文件中。
下面是对std::vector进行排序的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 2, 8, 1, 9};
// 使用std::sort对std::vector进行排序
std::sort(nums.begin(), nums.end());
// 输出排序后的结果
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
上述代码中,我们首先包含了<iostream>、<vector>和<algorithm>头文件。然后创建了一个std::vector<int>类型的nums,并初始化了一些整数元素。
接下来,我们使用std::sort函数对nums进行排序,传入nums.begin()和nums.end()作为排序范围。
最后,我们使用for循环遍历排序后的nums,并输出每个元素。
运行上述代码,输出结果为:1 2 5 8 9,表示nums已经按升序排列。