Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize inline vector of bool

Tags:

c++

vector

c++98

I am using this example to initialize the bool vector:

#include <iostream>
#include <map>
#include <vector>
using namespace std;

int main() {
 map<int, vector<bool> > myMap;
 vector<bool> one {true, true, false};
 myMap[2] = one;
 cout << myMap[2][0] << endl;
 cout << myMap[2][1] << endl;
 cout << myMap[2][2] << endl;
 return 0;
}

The only change I made in this code is using std::vector instead of vector and I now have:

std::map<int, std::vector<bool> >  m_links;
std::vector<bool> m_allFalse {false, false, false, false, false};

It tells me to use ; after m_allFalse. How can I get rid of this error?

I am using intel compiler 14, but without c++11.

like image 271
www Avatar asked Jul 31 '14 08:07

www


1 Answers

Problem is:

std::vector<bool> m_allFalse {false, false, false, false, false};

wrong syntax in standard C++. (maybe in C++11, I don't know)

You can use this instance:

std::vector<bool> m_allFalse(5, false); (*)

If you want C++11 edit your tag and follow @lakesh tip.

(*) this constructor is explained in vector documentation:

(2) fill constructor Constructs a container with n elements. Each element is a copy of val.

To initialize general boolean values at the beginning, you can use this way:

bool tempBool[] = { true, false, false, true };
std::vector<bool> variousBool ( tempBool, tempBool + sizeof(tempBool) / sizeof(bool) );

Knowing this, you could create your own vector class, simply inheriting from vector (if you want you can use template to extend to all types):

class PimpedVector : public std::vector<bool>  {
public:
  PimpedVector(const unsigned int& size, ...) {
    va_list args;
    va_start(args, size); 
    for ( size_t i = 0; i < size; ++i ) {
      bool b = va_arg(args, bool);
      this->push_back(b);
    }
  }
}

So from your main you can create a PimpedVector in this way:

PimpedVector p0(5, true, false, false, true, false);
like image 92
Luca Davanzo Avatar answered Sep 18 '22 06:09

Luca Davanzo