vector的初始化(5种不同方式)

  • 逐个push_back
// CPP program to create an empty vector
// and push values one by one.
#include 
#include 
using namespace std;

int main()
{
    // Create an empty vector
    vector vect;
    
    vect.push_back(10);
    vect.push_back(20);
    vect.push_back(30);

    for (int x : vect)
        cout << x << " ";
    return 0;
}
  • 指定大小并初始化所有值
// CPP program to create an empty vector
// and push values one by one.
#include 
#include 
using namespace std;
  
int main()
{
    int n = 3;
  
    // Create a vector of size n with
    // all values as 10.
    vector vect(n, 10);
  
    for (int x : vect)
        cout << x << " ";
  
    return 0;
}
  • 像数组一样初始化

// CPP program to initialize a vector like
// an array.
#include 
#include 
using namespace std;

int main()
{
    vector vect{ 10, 20, 30 };

    for (int x : vect)
        cout << x << " ";

    return 0;
}
  • 使用数组初始化

// CPP program to initialize a vector from
// an array.
#include 
#include 
using namespace std;
  
int main()
{
    int arr[] = { 10, 20, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    vector vect(arr, arr + n);
  
    for (int x : vect)
        cout << x << " ";
  
    return 0;
}
  • 使用另一个vector初始化

// CPP program to initialize a vector from
// another vector.
#include 
#include 
using namespace std;

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

    for (int x : vect2)
        cout << x << " ";

    return 0;
}

以上内容转载自: https://www.geeksforgeeks.org/initialize-a-vector-in-cpp-different-ways/,作者: Kartik


以下为vector和数组的互相初始化示例:

(转载自: https://www.iteye.com/blog/xiangjie88-871115, 作者:xiangjie88)

1. #include  
2. #include  
3. using namespace std;  
4. //数组初始化vector
5. int main()  
6. {  
7.         int a[]={1,2,3,4,5};  
8.         vector v(a,a+4);  
9.         for(vector::iterator iter=v.begin();  
10.                   iter!=v.end();  
11.                   ++iter)  
12.         {  
13.                 cout<<*iter< v;  
20.         for(int i=0;i<5;i++)  
21.             v.push_back(i);  
22.         int a[5];  
23.         for(int i=0;i

 

你可能感兴趣的:(c++,数据结构,leetcode)