CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

1. Member
Join Date
Mar 2018
Posts
37

## question about defining a vector

bb
Last edited by Kmilano; April 27th, 2018 at 03:46 AM.

2. Elite Member Power Poster
Join Date
Jan 2006
Location
Singapore
Posts
6,749

## Re: question about defining a vector

Code:
```std::vector<int> bit{ { 1,2,3,4} };
bit[1] = 0;
bit[2] = 0;
bit[3] = 0;```
why can't you just write:
Code:
`std::vector<int> bit{1, 0, 0, 0};`
?

3. Member
Join Date
Mar 2018
Posts
37

## Re: question about defining a vector

its possible to use binary numbers inside {}, but I'm looking a way to remove the whole {}
how I can remove it?

4. Member
Join Date
Feb 2017
Posts
323

## Re: question about defining a vector

Originally Posted by Kmilano
its possible to use binary numbers inside {}, but I'm looking a way to remove the whole {}
how I can remove it?
Std::vector has a constructor which allows you to first specify the wanted size of the vector and then also a default value for all index positions. For example if you want the bit vector to have size 4 with a 0 value at all index positions you can do,

Code:
`std::vector<int> bit(4,0);`
Note that index positions start from 0 so the bit vector can be accessed with indexes 0, 1, 2 and 3. Every other index will be out-of-bounds (unless you resize the vector of course).
Last edited by wolle; April 28th, 2018 at 03:27 AM.

5. ## Re: question about defining a vector

Consider

Code:
```#include <iostream>
#include <vector>
using namespace std;

int main()
{
constexpr size_t nobits = 4;
constexpr size_t nrows = (1 << (nobits - 1)) - 1;

std::vector<int> bit (nobits, 0);

for (size_t i = 0; i < nrows; ++i)
{
for (size_t x = i + 1, a = 1; (x > 0) && (a < nobits); x /=2)
bit[a++] = x % 2;

for (size_t e = nobits - 1; e > 0; --e)
cout << "Value syn[" << nobits - e - 1 << "]= " << bit[e] << "     ";

cout << "     decBits=" << i << endl;
}
}```
which displays

Code:
```Value syn[0]= 0    Value syn[1]= 0    Value syn[2]= 1         decBits=0
Value syn[0]= 0    Value syn[1]= 1    Value syn[2]= 0         decBits=1
Value syn[0]= 0    Value syn[1]= 1    Value syn[2]= 1         decBits=2
Value syn[0]= 1    Value syn[1]= 0    Value syn[2]= 0         decBits=3
Value syn[0]= 1    Value syn[1]= 0    Value syn[2]= 1         decBits=4
Value syn[0]= 1    Value syn[1]= 1    Value syn[2]= 0         decBits=5
Value syn[0]= 1    Value syn[1]= 1    Value syn[2]= 1         decBits=6```

6. ## Re: question about defining a vector

Originally Posted by Kmilano
bb
Otherwise it is absolutely unclear why you have started this thread!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•