What is the difference between std::set and std::vector?

前端 未结 5 1732
南笙
南笙 2020-12-02 05:04

I am learning STL now. I read about set container. I have question when you want to use set? After reading description of set it looks like it is u

5条回答
  •  攒了一身酷
    2020-12-02 05:46

    The simple difference is that set can contain only unique values, and it is sorted. So you can use it for the cases where you need to continuously sort the values after every insert / delete.

    set a;
    vector b;
    for (int i = 0; i < 10; ++i)
    {
        int val = rand() % 10;
        a.insert(val);
        b.push_back(val);
    }
    cout << "--SET---\n"; for (auto i : a) cout << i << ","; cout << endl;
    cout << "--VEC---\n"; for (auto j : b) cout << j << ","; cout << endl;
    

    The output is

    --SET---
    0,1,2,4,7,8,9,
    --VEC---
    1,7,4,0,9,4,8,8,2,4,
    

提交回复
热议问题