vector swap

Solutions on MaxInterview for vector swap by the best coders in the world

showing results for - "vector swap"
Irvin
01 Jan 2019
1std::iter_swap(arr.begin()+pos1,arr.begin()+pos2);
Butch
02 Oct 2019
1vector<T>().swap(x);   // clear x reallocating 
Dasia
21 Nov 2017
1#include <iostream>
2#include <vector>
3 
4template<class Os, class Co> Os& operator<<(Os& os, const Co& co) {
5    os << "{";
6    for (auto const& i : co) { os << ' ' << i; }
7    return os << " } ";
8}
9 
10int main()
11{
12    std::vector<int> a1{1, 2, 3}, a2{4, 5};
13 
14    auto it1 = std::next(a1.begin());
15    auto it2 = std::next(a2.begin());
16 
17    int& ref1 = a1.front();
18    int& ref2 = a2.front();
19 
20    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
21    a1.swap(a2);
22    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
23 
24    // Note that after swap the iterators and references stay associated with their
25    // original elements, e.g. it1 that pointed to an element in 'a1' with value 2
26    // still points to the same element, though this element was moved into 'a2'.
27}
Helena
29 Mar 2020
1// clearing vectors
2#include <iostream>
3#include <vector>
4
5int main ()
6{
7  std::vector<int> myvector;
8  myvector.push_back (100);
9  myvector.push_back (200);
10  myvector.push_back (300);
11
12  std::cout << "myvector contains:";
13  for (unsigned i=0; i<myvector.size(); i++)
14    std::cout << ' ' << myvector[i];
15  std::cout << '\n';
16
17  myvector.clear();
18  myvector.push_back (1101);
19  myvector.push_back (2202);
20
21  std::cout << "myvector contains:";
22  for (unsigned i=0; i<myvector.size(); i++)
23    std::cout << ' ' << myvector[i];
24  std::cout << '\n';
25
26  return 0;
27}
Manuel
09 Jul 2016
1vector1.swap<vector2>;
2//time complexity: O(1)
similar questions
queries leading to this page
vector swap