c++ - 为什么我不能使用集合作为 vector 变换操作的输出集合?

标签 c++

<分区>

当我对集合使用变换并使用 vector 存储输出时,它工作正常。但反之似乎行不通。

这是行不通的代码:

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

int multiply(int a) {
    return a * 2;
}
void print(int i) {
    cout << i << " ";
}
int main() {
    int mynumbers[] = { 3,9,2,4,1 };
    vector<int> v1(mynumbers, mynumbers + 5);
    set<int> s1(mynumbers, mynumbers + 5);
    transform(v1.begin(), v1.end(), s1.begin(), multiply);
    for_each(v1.begin(), v1.end(), print);
    cout << endl;
    for_each(s1.begin(), s1.end(), print);
}

最佳答案

作为@molbdnilo指出:

The elements of a set are immutable.

因此,无法覆盖现有元素。

但是,它可以通过例如一个std::insert_iterator :

#include <algorithm>
#include <iostream> 
#include <set>
#include <vector>

int main()
{
   std::vector<int> v = { 1, 2, 3, 4, 5 };
   std::set<int> s;
   std::transform(v.begin(), v.end(),
     std::insert_iterator<std::set<int>>(s, s.begin()),
     [](int x) { return x * 2; });
   for (int x : s) std::cout << ' ' << x;
}

输出:

 2 4 6 8 10

Live demo on coliru

关于c++ - 为什么我不能使用集合作为 vector 变换操作的输出集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71390905/

相关文章:

c++ - 树莓派 g++ : Ultrasonic sensor not working. ..!

c++ - 我是否需要在描述文件中为使用它的 R 包导入 RccpEigen,或者 "LinkingTo"就足够了吗?

c++ - clang 是否支持双字比较和交换操作?

c++ - LibTIFF:从 TIFF 图像中提取所有标签

c++ - 库没有链接,即使存在于链接目标中

c++ - QProcess导致内存泄漏

c++ - vector中包含的对象有什么要求

C++ msgsnd 和 msgrcv 陷休眠眠

c++ - Qt 5.0 Json编码

c++ - 有没有办法让我在 C++ 中通配一个 friend 类?