C++ STL中的DeQueAd()函数

这个 deque::assign() 在C++ STL中是一个内置函数,用于将值分配给相同或不同的DEQE容器。在同一程序中被多次调用时,该函数会销毁以前元素的值,并将新的元素集重新分配给容器。

null
  1. 语法:
    deque_name.assign(size, val)

    参数: 该函数接受以下两个参数:

    • 尺寸: 它指定要分配给容器的值的数量。
    • 瓦尔: 它指定要分配给容器的值。

    返回值: 函数不返回任何内容。

    以下程序说明了上述功能:

    项目1:

    // CPP program to demonstrate the
    // deque::assign() function
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
    deque< int > dq;
    // assign 5 values of 10 each
    dq.assign(5, 10);
    cout << "The deque elements: " ;
    for ( auto it = dq.begin(); it != dq.end(); it++)
    cout << *it << " " ;
    // re-assigns 10 values of 15 each
    dq.assign(10, 15);
    cout << "The deque elements: " ;
    for ( auto it = dq.begin(); it != dq.end(); it++)
    cout << *it << " " ;
    return 0;
    }

    
    

    输出:

    The deque elements: 10 10 10 10 10 
    The deque elements: 15 15 15 15 15 15 15 15 15 15
    

  2. 语法:
    deque1_name.assign(iterator1, iterator2)

    参数: 该函数接受以下两个参数:

    • 迭代器1: 它指定一个迭代器,该迭代器指向容器的起始元素(deque、array等),容器的元素将被传输到deque1。
    • 迭代器2: 它指定一个迭代器,该迭代器指向容器的最后一个元素(deque、array等),容器的元素将被传输到deque1

    返回值: 函数不返回任何内容。

    以下程序说明了上述功能:

    项目1:

    // CPP program to demonstrate the
    // deque::assign() function
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
    deque< int > dq;
    // assign 5 values of 10 each
    dq.assign(5, 10);
    cout << "The deque elements: " ;
    for ( auto it = dq.begin(); it != dq.end(); it++)
    cout << *it << " " ;
    deque< int > dq1;
    // assigns all elements from
    // the second position to deque1
    dq1.assign(dq.begin() + 1, dq.end());
    cout << "The deque1 elements: " ;
    for ( auto it = dq1.begin(); it != dq1.end(); it++)
    cout << *it << " " ;
    return 0;
    }

    
    

    输出:

    The deque elements: 10 10 10 10 10 
    The deque1 elements: 10 10 10 10
    

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享