How to check if 2d vector is empty

How do I check if all the "sub-vectors"(what is the correct term?) are empty?
if(???)error("Error : No values");
Excerpt of program :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 vector< vector<int> >week_days(no_of_days); // seven days for a week
for (int i = 0; i < no_of_days; ++i){
		vector<int>day;
		week_days.push_back(day); // putting in 7 day vectors into the week_days vector
	}
	
cout << "Enter day of week and value pairs\n";
string day = "sunday";
int value = 0;

for(day,value; cin >> day >> value;){
	day_value_push(day,value); // taking in inputs
}cout << value;
if(???)error("Error : No values");
Last edited on
Try this.
1
2
3
4
5
6
7
for (int i = 0; i < week_days.size(); i++)
  {
    if (week_days.at(i).size() == 0)
    {
      cout << " Vector " << i << " is empty" << endl;
    }
  }
1
2
3
4
5
6
7
8
9
const std::size_t num_days = 7 ;
std::vector< std::vector<int> > days(num_days) ;

// ...

static const auto empty = [] ( const auto& seq ) { return seq.empty() ; } ;

// #include <algorithm>  http://en.cppreference.com/w/cpp/algorithm/all_any_none_of
if( std::all_of( std::begin(days), std::end(days), empty ) ) std::cout << "no values\n" ;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// http://coliru.stacked-crooked.com/a/9e2a20caccdb14f1
#include <iostream>
#include <string>
#include <vector>

template <typename ContainerType>
bool fully_populated(const ContainerType& container)
{
    for (auto& contained : container)
        if (contained.empty()) return false;

    return true;
}

int main()
{
    using std::vector;
    using std::cout;
    using std::cin;
    using std::string;

    const unsigned no_of_days = 7;

    vector< vector<int> >week_days(no_of_days); // seven days for a week

    // redundant:
    //for (int i = 0; i < no_of_days; ++i) {
    //    vector<int>day;
    //    week_days.push_back(day); // putting in 7 day vectors into the week_days vector
    //}

    for (unsigned i = 0; i < no_of_days - 1; ++i)
        week_days[i].push_back(i);

    if (!fully_populated(week_days))
        std::cout << "There is at least one week day with no associated values.\n";
    else
        std::cout << "Fully populated.\n";


    week_days[6].push_back(6);

    if (!fully_populated(week_days))
        std::cout << "There is at least one week day with no associated values.\n";
    else
        std::cout << "Fully populated.\n";
}




Topic archived. No new replies allowed.