Why is it workable? There are two different strings "testString"
but the vector size is allocated correctly.
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::vector<char> str;
str.assign(std::begin("testString"), std::end("testString"));
copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout, " "));
std::cout<<str.size();
return 1;
}
Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.
when you create a vector it gets default initialized, so it's up to you if you want to initialize it with user default values or not. You will always get an empty vector container if you don't initialize it.
A vector, once declared, has all its values initialized to zero.
This post provides basic examples of vector initialization ignoring all scenarios where the content of the new vector is copied from another array or container. A std::vector can be initialized using the std::vector fill constructor if we need a vector containing M elements that are all equal to a given value or object.
vector::begin() begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container.
vector::end () function is a bidirectional iterator used to return an iterator pointing to the last element of the container. Begin Initialize the vector v. Declare the vector v1 and iterator it to the vector. Insert the elements of the vector.
But you are right that if you want to initialize an empty vector and a non-empty vector you will have to use different constructs. Since C++11 this is a non-issue as you can use the initializer list constructor #include <vector> using std::vector; ... vector<int> vec1 { 10, 20, 30 }; // or vector<int> vec2 = { 10, 20, 30 };
You got lucky and compiler performed string pooling optimisation. Note that what you doing is still undefined behaviour and with different compiler or different compiler settings you will not be so lucky. Do not do that again.
The two identical literal strings have most likely been combined into a single one in memory so the begin and end refer to the same string.
This only works by 'accident' in your program though...
This is a somewhat related How Do C++ Compilers Merge Identical String Literals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With