首先,您應該計算源數組中滿足條件的元素數量,然後爲元素分配足夠的內存。
這裏是一個示範項目
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
const size_t N1 = 11;
const size_t N2 = 2;
int * val = new int[N1] { 1, 1, 2, 2, 2, 2, 3, 4, 5, 5, 5 };
int * invalid = new int[N2] { 2, 5 };
int *valid = nullptr;
auto n = std::count_if(val, val + N1,
[=](int x) { return !std::binary_search(invalid, invalid + N2, x); });
if (n)
{
valid = new int[n];
std::copy_if(val, val + N1, valid,
[=](int x) { return !std::binary_search(invalid, invalid + N2, x); });
}
if (valid) std::copy(valid, valid + n, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
它的輸出是
1 1 3 4
您可以使用標準算法std::binary search
如果無效的數組有很多元素,或者你可以只寫lambda表達式像
[=](int x) { return x != invalid[0] && x != invalid[1]; }
例如
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
const size_t N1 = 11;
const size_t N2 = 2;
int * val = new int[N1] { 1, 1, 2, 2, 2, 2, 3, 4, 5, 5, 5 };
int * invalid = new int[N2] { 2, 5 };
int *valid = nullptr;
auto is_valid_element = [=](int x) { return x != invalid[0] && x != invalid[1]; };
auto n = std::count_if(val, val + N1, is_valid_element);
if (n)
{
valid = new int[n];
std::copy_if(val, val + N1, valid, is_valid_element);
}
if (valid) std::copy(valid, valid + n, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
編譯器應支持C++ 2011
'delete [] val'等被忽略爲了清晰起見 – SemtexB
可以使用另一個數組來存儲所需的值嗎? –
@BlackBird:你究竟是什麼意思?不要在我的示例中將所需的值存儲在另一個數組中? val會被部分複製到'valid'。 – SemtexB