gpt4 book ai didi

c++ - 插入器迭代器,可根据谓词插入不同的容器

转载 作者:行者123 更新时间:2023-12-02 10:03:58 25 4
gpt4 key购买 nike

可以说我有一个数字 vector ,我想创建两个 vector 以将奇数和偶数分开。轻松实现以下目的:

std::vector<int> odds;
std::vector<int> evens;
std::vector<int> numbers;
for (int number : numbers) {
if isOdd(number)
odds.push_back(number);
else
evens.push_back(number);
}

我想知道是否有任何类型的inserter_iterator可以做到这一点,所以我可以写一些
std::vector<int> odds;
std::vector<int> evens;
std::vector<int> numbers;

auto pred = [](int i) { return isOdd(i) ? True : False;};
auto identity = [](int i) {return i;};
std::transform(std::begin(numbers), std::end(numbers), some_inserter(odd, evens, pred), identity);

这只是出于好奇,我试图了解算法和迭代器的工作方式。基于范围的解决方案也是有效的。

最佳答案

您可以使用std::partition_copy算法,如下所示https://en.cppreference.com/w/cpp/algorithm/partition_copy

int main() {
std::vector vec = {1, 2, 3, 4, 5, 6};//the vector to be partitioned
std::vector<int> odds(vec.size());//will hold odds (to have the sam size as the original (the maximum case) )
std::vector<int> evens(vec.size());//will hold evens

auto [oddsEnd, evensEnd] =
std::partition_copy(vec.begin(), vec.end(), odds.begin(), evens.begin(), [](int i){return i%2!=0;});//will copy at the front (won't insert at the back)
odds.erase(oddsEnd, odds.end());//to erase the undesired excess
evens.erase(evensEnd, evens.end());//to erase the undesired excess

}

或使用 std::back_inserter https://en.cppreference.com/w/cpp/iterator/back_inserter(请参阅评论)
int main() {
std::vector vec = {1, 2, 3, 4, 5, 6};//the vector to be partitioned
std::vector<int> odds;//will hold odds
std::vector<int> evens;//will hold evens

std::partition_copy(vec.begin(), vec.end(), std::back_inserter(odds), std::back_inserter(evens), [](int i){return i%2!=0;});//will insert

}

关于c++ - 插入器迭代器,可根据谓词插入不同的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com