提交 a43fac35 编写于 作者: Y Yu Yang

Fix empty Vector foreach

Fix #8368
上级 4f4abfa3
...@@ -106,9 +106,9 @@ class Vector { ...@@ -106,9 +106,9 @@ class Vector {
// std::vector iterator methods. Based on CPU data access method // std::vector iterator methods. Based on CPU data access method
size_t size() const { return size_; } size_t size() const { return size_; }
T* begin() { return &this->operator[](0); } T* begin() { return size() == 0 ? &EmptyDummy() : &this->operator[](0); }
T* end() { return &this->operator[](size()); } T* end() { return size() == 0 ? &EmptyDummy() : &this->operator[](size()); }
T& front() { return *begin(); } T& front() { return *begin(); }
...@@ -118,12 +118,12 @@ class Vector { ...@@ -118,12 +118,12 @@ class Vector {
return *it; return *it;
} }
const T* begin() const { return &this->operator[](0); } const T* begin() const {
const T* end() const { return &this->operator[](size()); } return size() == 0 ? &EmptyDummy() : &this->operator[](0);
}
const T* cbegin() const { return begin(); } const T* end() const {
return size() == 0 ? &EmptyDummy() : &this->operator[](size());
const T* cend() const { return end(); } }
const T& back() const { const T& back() const {
auto it = end(); auto it = end();
...@@ -240,16 +240,18 @@ class Vector { ...@@ -240,16 +240,18 @@ class Vector {
// implicit cast operator. Vector can be cast to std::vector implicitly. // implicit cast operator. Vector can be cast to std::vector implicitly.
operator std::vector<T>() const { operator std::vector<T>() const {
std::vector<T> result; std::vector<T> result;
if (size() == 0) {
result.resize(size()); result.resize(size());
std::copy(begin(), end(), result.begin()); std::copy(begin(), end(), result.begin());
}
return result; return result;
} }
bool operator==(const Vector<T>& other) const { bool operator==(const Vector<T>& other) const {
if (size() != other.size()) return false; if (size() != other.size()) return false;
auto it1 = cbegin(); auto it1 = begin();
auto it2 = other.cbegin(); auto it2 = other.begin();
for (; it1 < cend(); ++it1, ++it2) { for (; it1 < end(); ++it1, ++it2) {
if (*it1 != *it2) { if (*it1 != *it2) {
return false; return false;
} }
...@@ -358,6 +360,11 @@ class Vector { ...@@ -358,6 +360,11 @@ class Vector {
} }
} }
static T& EmptyDummy() {
static T dummy = T();
return dummy;
}
mutable int flag_; mutable int flag_;
mutable Tensor cpu_vec_; mutable Tensor cpu_vec_;
mutable Tensor cuda_vec_; mutable Tensor cuda_vec_;
......
...@@ -98,3 +98,9 @@ TEST(mixed_vector, InitWithCount) { ...@@ -98,3 +98,9 @@ TEST(mixed_vector, InitWithCount) {
ASSERT_EQ(vec[i], 10); ASSERT_EQ(vec[i], 10);
} }
} }
TEST(mixed_vector, ForEach) {
vec<int> tmp;
for (auto& v : tmp) {
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册