folly: small_vector: emplace_back for iterator constructor (compat with std::vector)
authorLucian Grijincu <lucian@fb.com>
Thu, 10 Sep 2015 00:22:27 +0000 (17:22 -0700)
committerfacebook-github-bot-4 <folly-bot@fb.com>
Thu, 10 Sep 2015 01:20:17 +0000 (18:20 -0700)
Summary: This works:
  std::vector<T*> v;
  std::vector<std::unique_ptr<T>> uv(v.begin(), v.end())

Make it work for small_vector as well.

Reviewed By: @ot, @Gownta

Differential Revision: D2426919

folly/small_vector.h
folly/test/small_vector_test.cpp

index ca62f1471ad22fb2d27d551f4da4d9fc19e569ad..df237553e3f6c1e9d1cc8ecc815c6032b1f1bee2 100644 (file)
@@ -883,7 +883,7 @@ private:
       // With iterators that only allow a single pass, we can't really
       // do anything sane here.
       while (first != last) {
-        push_back(*first++);
+        emplace_back(*first++);
       }
       return;
     }
index cd365beaac09d2479dc7f9bd32df70075f1ec864..f78d34ee0a7b755cfe529497b7f1b38beaf1de75 100644 (file)
 
 #include <folly/small_vector.h>
 
-#include <gtest/gtest.h>
-#include <string>
-#include <memory>
 #include <iostream>
+#include <iterator>
 #include <limits>
+#include <memory>
+#include <sstream>
+#include <string>
+#include <vector>
 
 #include <boost/algorithm/string.hpp>
+#include <gtest/gtest.h>
 
 #include <folly/Conv.h>
 
@@ -802,3 +805,32 @@ TEST(small_vector, RVPushValueInsideVector) {
     ASSERT_EQ(1, v.back().value);
   }
 }
+
+TEST(small_vector, EmplaceIterCtor) {
+  std::vector<int*> v{new int(1), new int(2)};
+  std::vector<std::unique_ptr<int>> uv(v.begin(), v.end());
+
+  std::vector<int*> w{new int(1), new int(2)};
+  small_vector<std::unique_ptr<int>> uw(v.begin(), v.end());
+}
+
+TEST(small_vector, InputIterator) {
+  std::vector<int> expected{125, 320, 512, 750, 333};
+  std::string values = "125 320 512 750 333";
+  std::istringstream is1(values);
+  std::istringstream is2(values);
+
+  std::vector<int> stdV{std::istream_iterator<int>(is1),
+                        std::istream_iterator<int>()};
+  ASSERT_EQ(stdV.size(), expected.size());
+  for (size_t i = 0; i < expected.size(); i++) {
+    ASSERT_EQ(stdV[i], expected[i]);
+  }
+
+  small_vector<int> smallV{std::istream_iterator<int>(is2),
+                           std::istream_iterator<int>()};
+  ASSERT_EQ(smallV.size(), expected.size());
+  for (size_t i = 0; i < expected.size(); i++) {
+    ASSERT_EQ(smallV[i], expected[i]);
+  }
+}