jeudi 26 septembre 2019

How to conditionally add element to std::array - C++11

I have a simple program:

#include <array>
#include <iostream>
#include <functional>
#include <algorithm>

using namespace std;

int main(){
    array<int, 5> myArr = {3, 10, 0, 5, 7};
    int badNum = 0;
    for(int item : myArr){
        cout << item << endl;
    }

    cout << "\n" << endl;
    cout << "\n" << endl;

    sort(myArr.begin(), myArr.end(), greater<int>());

    for(int item : myArr){
        cout << item << endl;
    }

    array<int, 3> goodThree;

    for (unsigned int i = 0; i < myArr.size(); i++){
        if(myArr[i] != badNum){
            // goodThree.append(myArr[i]); <-- This is where I am stuck
        }
    }

}

I am stuck on trying to add an element to a std::array. I know in std::vector I can use push_back method, but on a std:array, how to add elements to it? I am coming from Python 3.x where we have the append method for a list.

I have looked at the C++ std::array documentation but there is no method for adding a single element.

I have also looked at:

http://www.cplusplus.com/forum/beginner/67707/

http://www.cplusplus.com/forum/beginner/86394/

http://www.cplusplus.com/forum/beginner/152125/

But these are all for vectors or the primitive int[5] myArr types, not std::array.

Aucun commentaire:

Enregistrer un commentaire