diff --git a/README.md b/README.md index 164b24c..d63dbe5 100644 --- a/README.md +++ b/README.md @@ -113,5 +113,6 @@ int main(int argc, char *argv[]) { | [`v.push_back(value)`](https://en.cppreference.com/w/cpp/container/vector/push_back) | `cvector_push_back(v, value)` | | [`v.pop_back()`](https://en.cppreference.com/w/cpp/container/vector/pop_back) | `cvector_pop_back(v)` | | [`v.reserve(new_cap)`](https://en.cppreference.com/w/cpp/container/vector/reserve) | `cvector_reserve(v, new_cap)` | +| [`v.resize(count)`](https://en.cppreference.com/w/cpp/container/vector/resize) | `cvector_resize(v, count)` | | [`v.swap(other)`](https://en.cppreference.com/w/cpp/container/vector/swap) | `cvector_swap(v, other)` | | [`std::vector other = v;`](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) | `cvector(int) other; cvector_copy(v, other);` | diff --git a/cvector.h b/cvector.h index 20541aa..af869be 100644 --- a/cvector.h +++ b/cvector.h @@ -450,4 +450,30 @@ typedef struct cvector_metadata_t { #define cvector_back(vec) \ ((vec) ? ((cvector_size(vec) > 0) ? cvector_at(vec, cvector_size(vec) - 1) : NULL) : NULL) +/** + * @brief cvector_resize - resizes the container to contain count elements. + * @param vec - the vector + * @param count - new size of the vector + * @param value - the value to initialize new elements with + * @return void + */ +#define cvector_resize(vec, count, value) \ + do { \ + if (vec) { \ + size_t cv_sz_count__ = (size_t)(count); \ + size_t cv_sz__ = cvector_vec_to_base(vec)->size; \ + if (cv_sz_count__ > cv_sz__) { \ + cvector_reserve((vec), cv_sz_count__); \ + cvector_set_size((vec), cv_sz_count__); \ + do { \ + (vec)[cv_sz__++] = (value); \ + } while (cv_sz__ < cv_sz_count__); \ + } else { \ + while (cv_sz_count__ < cv_sz__--) { \ + cvector_pop_back(vec); \ + } \ + } \ + } \ + } while (0) + #endif /* CVECTOR_H_ */ diff --git a/unit-tests.c b/unit-tests.c index e3bc8db..b7db783 100644 --- a/unit-tests.c +++ b/unit-tests.c @@ -325,6 +325,30 @@ UTEST(test, vector_shrink_to_fit) { cvector_free(a); } +UTEST(test, vector_resize) { + cvector_vector_type(int) a = NULL; + + cvector_push_back(a, 1); + cvector_push_back(a, 2); + cvector_push_back(a, 3); + + cvector_resize(a, 50, 4); + ASSERT_EQ(cvector_size(a), (size_t)50); + ASSERT_EQ(a[1], 2); + ASSERT_EQ(a[30], 4); + ASSERT_EQ(a[49], 4); + ASSERT_EQ(a[49], 4); + + cvector_resize(a, 10, 8); + ASSERT_EQ(cvector_size(a), (size_t)10); + ASSERT_EQ(a[2], 3); + + cvector_resize(a, 0, 0); + ASSERT_EQ(cvector_size(a), (size_t)0); + + cvector_free(a); +} + struct data_t { int num; int a, b, c, d;