Search code examples
c++algorithmstdvectorswapstd-pair

Swap two values in a vector


I'm trying to find the most left point on a graph of a random set of points. For Example, out of the points (3, 5) (5, 2) (8, 7) (1, 3), the most left point would be (1, 3). Once I do this, I have to put the most left point in spot 0 of a vector. I am having trouble switching two variables since I don't know which spot mostLeft is originally from. mostLeft is a node containing two ints.

I have tried using

    swap(list[0], mostLeft)

but it just copies mostLeft twice.

I have also tried

   Point temp = list[0];
   list.erase(remove(list.begin(), list.end(). mostLeft), list.end());
   list[0] = left;
   list.push_back(temp);

but this gives me the error "cannot convert vector to const char* for argument to remove". I got the second block of code from online. I'm unsure how it would work but I kept seeing it pop up so I tried it.

Is there an easy way to swap these values or do I have to manually iterate through the vector and find the value.


Solution

  • If I have understood correctly what you are trying to achieve then you can use the following approach

    #include <iostream>
    #include <utility>
    #include <vector>
    #include <algorithm>
    
    int main()
    {
        std::vector<std::pair<int, int>> v = 
        {
            { 3, 5 }, { 5, 2 }, { 8, 7 }, { 1, 3 }
        };
    
        for (const auto &p : v)
        {
            std::cout << "(" << p.first << ", " << p.second << ") ";
        }
        std::cout << std::endl;
    
        auto mostLeft = [](const auto &a, const auto &b) { return a.first < b.first; };
    
        std::swap(v[0], *std::min_element(v.begin(), v.end(), mostLeft));
    
        for (const auto &p : v)
        {
            std::cout << "(" << p.first << ", " << p.second << ") ";
        }
        std::cout << std::endl;
    }
    

    The program output is

    (3, 5) (5, 2) (8, 7) (1, 3)
    (1, 3) (5, 2) (8, 7) (3, 5)