stl向量_如何在C ++ STL中将数组元素复制到向量?
stl向量
Given an array and we have to copy its elements to a vector in C++ STL.
給定一個數組,我們必須將其元素復制到C ++ STL中的向量。
將數組元素復制到向量 (Copying array elements to a vector)
In C++ STL, we can copy array elements to a vector by using the following ways,
在C ++ STL中,我們可以使用以下方式將數組元素復制到向量中 :
Assigning array elements while declaring a vector
在聲明向量的同時分配數組元素
When we declare a vector we can assign array elements by specifying the range [start, end] of an array.
聲明向量時,可以通過指定數組的范圍[開始,結束]來分配數組元素。
vector<type> vector_name(array_start, array_end);By using copy function
通過使用復制功能
copy() function is a library function of algorithm header it can be used to copy an array’s elements to a vector by specifying the array range [start, end] and an iterator pointing to the initial position (from where we want to assign the content) of the vector.
copy()函數是算法標頭的庫函數,可通過指定數組范圍[start,end]和指向初始位置的迭代器(用于從中分配內容)將其復制到向量中向量)。
vector<type> vector_name(size);std::copy(array_start, array_end, vector_start_iterator);Note: To use vector – include <vector> header, and to use copy() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.
注意:要使用vector –包含<vector>頭文件,而要使用copy()函數 –包含<algorithm>頭文件,或者我們可以簡單地使用<bits / stdc ++。h>頭文件。
C ++ STL程序將數組元素復制到向量 (C++ STL program to copy array elements to a vector )
#include <iostream> #include <algorithm> #include <vector> using namespace std;int main() {//an arrayint arr[] = { 10, 20, 30, 40, 50 };//assigning array to vector while declaring itvector<int> v1(arr + 0, arr + 5);//declaring an arrray first//and then copy the array contentvector<int> v2(5);copy(arr + 0, arr + 5, v2.begin());//printing the vectorscout << "vector (v1): ";for (int x : v1)cout << x << " ";cout << endl;cout << "vector (v2): ";for (int x : v2)cout << x << " ";cout << endl;return 0; }Output
輸出量
vector (v1): 10 20 30 40 50 vector (v2): 10 20 30 40 50翻譯自: https://www.includehelp.com/stl/how-to-copy-array-elements-to-a-vector.aspx
stl向量
總結
以上是生活随笔為你收集整理的stl向量_如何在C ++ STL中将数组元素复制到向量?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python | 如何强制除法运算为浮点
- 下一篇: 计算机图形学图形旋转_计算机图形学翻译