Edit: I added a method using std::unique_ptr
.
If C++17 is available to you, how about replacing v
's elements by std::optional<int>
as follows ?
#include <iostream>
#include <optional>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::optional<int>> v(10);
for (std::size_t i = 0; i<7; ++i){
v[i] = i;
}
std::cout
<< (v.size() - std::count(v.cbegin(), v.cend(), std::nullopt))
<< " elements have been filled and I still have "
<< std::count(v.cbegin(), v.cend(), std::nullopt)
<< " available."
<< std::endl << std::endl;
for(const auto v_i : v)
{
if(v_i.has_value()){
std::cout << v_i.value() << " ";
}
}
return 0;
}
But if you are constrained by an older version, I think that std::unique_ptr
would be a solution.
DEMO:
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::unique_ptr<int>> v(10);
for (std::size_t i = 0; i<7; ++i){
v[i] = std::make_unique<int>(i);
}
std::cout
<< (v.size() - std::count(v.cbegin(), v.cend(), nullptr))
<< " elements have been filled and I still have "
<< std::count(v.cbegin(), v.cend(), nullptr)
<< " available."
<< std::endl << std::endl;
for(const auto& v_i : v)
{
if(v_i){
std::cout << *v_i << " ";
}
}
return 0;
}
Finally, I found similar approaches here.