如何有条件地将元素添加到 std::array - C++11

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

本文关键字:std array C++11 添加 有条件 元素      更新时间:2023-10-16

>我有一个简单的程序:

#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, 4> goodFour;
for (unsigned int i = 0; i < myArr.size(); i++){
if(myArr[i] != badNum){
// goodThree.append(myArr[i]); <-- This is where I am stuck
}
}
}

我一直在尝试将元素分配给std::array.我知道std::vector我可以使用push_back方法,但是在std:array上,如何分配给下一个(尚未分配(元素?我来自Python 3.x,我们有append方法进行list。我不是在尝试更改数组的大小,而是尝试用值填充分配的空间。

我看过:

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

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

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

但这些都是针对向量或原始int[5] myArr类型,而不是std::array.

如果你只想要前三个好的数字,你可以维护一个指向下一个索引的指针,以插入:

for (int i = 0, k = 0; k < 3 && i < myArr.size(); i++) {
if (myArr[i] != badNum) {
goodThree[k++] = myArr[i];
}
}

如果你想要所有好的数字,你可以使用std::vector并调用它的push_back方法:

std::vector<int> goodThree;
for (int i = 0; i < myArr.size(); i++) {
if (myArr[i] != badNum) {
goodThree.push_back(myArr[i]);
}
}

std::array的大小在编译时是固定的。如果需要在运行时附加另一个值,则必须使用std::vector(或类似的东西(。最接近"追加"到std::array的方法是将其内容复制到一个数组中,其中包含另一个包含"追加"值的元素。您可以使用一些模板元编程技术来简化此操作:

template <typename T, std::size_t N, typename X, std::size_t... I>
std::array<T, N + 1> push_back(std::array<T, N> const& a, X&& x, std::index_sequence<I...>) {
return {std::get<I>(a)..., std::forward<X>(x)};
}
template <typename T, std::size_t N, typename X>
std::array<T, N + 1> push_back(std::array<T, N> const& a, X&& x) {
return detail::push_back(a, std::forward<X>(x), std::make_index_sequence<N>());
}

使用示例:

std::array<int, 2> a = {1, 2};
std::array<int, 3> b = push_back(a, 3);
for (int x : b) {
std::cout << x << "n";
}

std::array的大小是在编译时设置的。这意味着不能在运行时将值"追加"到std::array。但是,您可以通过自己的程序逻辑跟踪数组"包含"多少值。例如:

std::array<int, 5> a = {1, 2, 3, 4, 5};
std::array<int, 4> b;
std::size_t n = 0;
for (int x : a) {
if (x != 2) {
if (n < std::size(a) - 1) {
b[n++] = x;
} else {
throw std::out_of_range("array is full");
}
}
}