0

I'm learning how to use vectors in C++ using this post and they gave the example below on populating a vector using an array. The syntax is a bit confusing though.

#include <iostream>
#include <string>
#include <vector>

int main() {
    // Array of string objects
    std::string arr[] = {
        "first",
        "sec",
        "third",
        "fourth"
    };

    // Vector with a string array
    std::vector < std::string > vecOfStr(arr,arr +sizeof(arr) / sizeof(std::string)); //This line is confusing
    for (std::string str: vecOfStr)
        std::cout << str << std::endl;
}

As far as my understanding goes, right after the variable name for the vector there comes the size of the vector. I would imagine that would have simply been sizeof(arr) / sizeof(std::string) but instead it's arr,arr +sizeof(arr) / sizeof(std::string). Can anyone tell me why?

2
  • 1
    std::vector < std::string > vecOfStr(std::begin(arr), std::end(arr)); Commented Jan 11, 2020 at 14:56
  • 1
    You want to look at overloading. std::vector's constructor is overloaded, which means that, depending on the number and types of arguments it received, the behaviour is different. Commented Jan 11, 2020 at 15:25

2 Answers 2

6

std::vector has multiple constructors which you can choose from. One of the constructors indeed receives the vector's length. In your example, a different constructor is being used. One which receives two iterators.

You pass the constructor two pointers of std::string which serve as iterators.

The addition and division operators are just pointers arithmetics.

Sign up to request clarification or add additional context in comments.

Comments

3

Use a std::array. Then you can populate the vector as

std::vector<std::string> vecOfStr(arr.begin(), arr.end());

Get out of the habit of using C-style arrays.

Also; if you insist on using C-style arrays, then, at least, use std::size() if you need the number of elements.

2 Comments

I'm just following the tutorial, I'm guessing C-style arrays are bad?
@S.Ramjit Usually, you want to avoid using c-style arrays in c++ code. If you still need to use it, use 'std::array' instead, like Jesper suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.