1

I am beginner in c++. Can someone let me know how to insert elements while maintaining sorted order for a STL::vector(without inbuilt sort() functions )

I am getting segmentation fault.

Please find my code in below:

Code:

int main()
{
    vector<int> k;

    k.insert(k.begin(), 2);

    k.insert(k.begin(), 1);
    k.insert(k.begin(), 38);

    k.insert(k.begin(), 4);


    k.insert(k.begin(), 50);

    int s = rand() % 40;

    for (auto p = k.begin(); p != k.end(); p++)
    {
        if (s > *p)
        {
            auto m = k.begin()++;
            k.insert(m, s);
        }
        else
        {
            k.insert(k.begin(), s);
        }
    }

    for (auto p = k.begin(); p != k.end(); p++)
    {
        cout << *p << " ";
    }
}
François Andrieux
  • 24,129
  • 6
  • 46
  • 72
rina ber
  • 11
  • 1
  • I suggest you take a look at [this](http://en.cppreference.com/w/cpp/container/priority_queue) – Seeker Oct 26 '17 at 19:20
  • Is is possible to implement without using built in functions...becuase I can use a simple function like below......but I want to do it without using functions. sort(k.begin( ), k.end( ),[](const int & a, const int & b) { return a.value() < b.value(); }); – rina ber Oct 26 '17 at 19:28
  • just use `std::lower_bound` to find position in already sorted vector, but your question and your code does not match. – Slava Oct 26 '17 at 19:28
  • I want to sort this vector using an iterator... – rina ber Oct 26 '17 at 19:31
  • 1
    @rinaber -- *I want to sort this vector using an iterator...* -- You start out with an unsorted vector. So why aren't you sorting your original vector first, before you start adding random numbers to it? Also, `std::sort` uses iterators, so saying "sort this vector using an iterator" -- that is what `std::sort` does. – PaulMcKenzie Oct 26 '17 at 19:38

0 Answers0