C++ return the sum of the 2 smallest elements in a vector Here is the description of the problem from codewars:

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.
For example, when an array is passed like [19,5,42,2,77], the output should be 7.
[10,343445353,3453445,3453545353453] should return 3453455.
Hint: Do not modify the original array.

And this is my solution which passed all tests.
// Returns the index of the smallest number.
int smallest(std::vector&lt;int&gt; numbers) {
  int smallest = 1;
  for(int i = 0; i &lt; numbers.size(); i++) 
  {
    if(numbers[i] &lt; numbers[smallest]) {
      smallest = i;
    }
  }
  return smallest;
}

long sumTwoSmallestNumbers(std::vector&lt;int&gt; numbers)
{
  int firstIndex = smallest(numbers);
  uint64_t first = numbers[smallest(numbers)];
  numbers.erase(numbers.begin() + firstIndex);

  uint64_t second = numbers[smallest(numbers)];

  return first + second;
}

While it's fairly fast and simple I feel like there is a way to do it while only looping over the list once and the hint about not modifying it seems to suggest that.
Missing headers

This code needs to include &lt;vector&gt; (for std::vector&lt;int&gt;) and &lt;cstdint&gt; (for std::uint64_t).

Don't pass collections by value

The function signature int smallest(std::vector&lt;int&gt; numbers) makes a copy of the input vector.  If we follow the hint that we shouldn't modify it, we can pass by reference:

int smallest(const std::vector&lt;int&gt;&amp; numbers);


Even better would be to act like the standard algorithms, and not depend on the type of container at all:

template &lt;typename Iter&gt;
typename std::iterator_traits&lt;Iter&gt;::value_type
smallest(Iter first, Iter last);


Use the correct type for indexing

When indexing an collection, int isn't necessarily adequate.  Instead you should be using std::vector&lt;int&gt;::size_type (which is the same as std::size_t on many implementations):

using index_t = std::vector&lt;int&gt;::size_type;
for (index_t i = 0;  i &lt; numbers.size();  ++i)


Use the standard algorithms

#include &lt;algorithm&gt;


That gives you std::partial_sort_copy().  You can fill a two-element array with the lowest two elements:

using std::begin;
using std::end;
int first_two[2];

std::partial_sort_copy(begin(nums), end(nums),
                       begin(first_two), end(first_two));

return std::accumulate(begin(first_two), end(first_two), 0);


(Yes, std::accumulate() is overkill, but it does show how to generalize this).