Why do I get one element in b
instead of two? In a
I get one as expected and in c
three elements as expected. The one with the two values is somehow a special case.
#include <string>
#include <vector>
#include <iostream>
void print(const std::string& name, const std::vector<std::string>& v)
{
std::cout << name << ' ' << v.size() << '\n';
for (const auto& str : v) {
std::cout << str << '\n';
}
std::cout << "\n";
}
int main()
{
std::vector<std::string> a = {{"str1"}};
std::vector<std::string> b = {{"str1", "str2"}};
std::vector<std::string> c = {{"str1", "str2", "str3"}};
print("a", a);
print("b", b);
print("c", c);
return 0;
}
This prints:
a 1
str1
b 1
str1
c 3
str1
str2
str3
I guess it has something to do with this overload of the vector ctor.
template< class InputIt >
vector( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
I used clang 9.0.0 with -std=c++17 -O2 -Wall
as flags.
What did the compiler do in the case of b
? Why did it decide it's an iterator in one case and initializer list in the other cases? Is my sample code well defined or does it have UB?