Ask coding questions

← Back to all posts
C++
RiaanSheth (3)

I want to learn how to use vectors in c++ I have a few ideas of where I want to implement it. Can someone please help.

Comments
hotnewtop
mwilki7 (1133)

Here is an example of how you can use vectors in your code:
(you can treat them a lot like arrays)

For your list of letters

bool Letter1, Letter2, Letter3, Letter4, Letter5, Letter6, Letter7, Letter8;
Letter1 = false, Letter2 = false, Letter3 = false, Letter4 = false, Letter5 = false, Letter6 = false, Letter7 = false, Letter8 = false;

Using vectors

vector<bool> letters;
int number_of_letters = 8;
for (int i = 0; i < number_of_letters; i++)
{
    letters.push_back(false);
}

For your list of letters in an if statement:

if (Letter1==true && Letter2==true && Letter3==true && Letter4==true && Letter5 == true && Letter6 == true && Letter7 == true && Letter8 == true)

Using vectors (and an extra function)

bool allLettersTrue(vector<bool> letters)
{
    for (auto letter: letters)
    {
        if (letter == false)
        {
            return false;
        }
    }
    return true;
}
...
...
...
...
if (allLettersTrue(letters))
{
    ...
    ...
}
mwilki7 (1133)

More about how to use vectors:
(fancy arrays that resize themselves)

/////////////////////////////////
// 1. Creating a vector of chars
// All vectors start with a size of 0 if you initialize them like this
vector<char> arr;

////////////////////////////////
// Now the vector looks like: //
// arr: [] <-- empty          //
////////////////////////////////

/////////////////////////////////
// 2. Adding new elements to the vector
arr.push_back('a'); // index 0
arr.push_back('b'); // index 1
arr.push_back('c'); // index 2
arr.push_back('d'); // index 3
arr.push_back('e'); // index 4

///////////////////////////////////////////////////////
// Now the vector looks like:                        //
// arr: ['a', 'b', 'c', 'd', 'e'] <-- 5 chars inside //
///////////////////////////////////////////////////////

/////////////////////////////////
// 3. Changing the vector
arr[0] = '@';
arr[1] = '3';

////////////////////////////////////
// Now the vector looks like:     //
// arr: ['$', '3', 'c', 'd', 'e'] //
////////////////////////////////////

///////////////////////////////////
// 4. Looping through the vector
for (auto element: arr)
{
    cout << element;
}

//////////////////////////////////
// 5. Two-dimensional vectors:
vector<vector<char>> board;

// Initializing 2D vectors
for (int i = 0; i < array_size; i++)
{
    vector<char> temp;
    for (int j = 0; j < array_size; j++)
    {
        temp.push_back('+'); // filling it with '+' symbols
    }
    board.push_back(temp);
}

// Changing an element in a 2d vector
board[0][1] = 'd';

Here are additional sources:
https://medium.com/the-renaissance-developer/c-standard-template-library-stl-vector-a-pretty-simple-guide-d2b64184d50b