Differences between String and Vector Element <string>

I am new to programming. I am learning vectorin C ++. I wonder why it string s = 42;causes an error, but

vector<string>vec(3);
vec[0] = 42;

no. Thank!

+4
source share
2 answers

std::vectorhas nothing to do with it, your sample with std::vectorlooks like

std::string s;
s = 42;

but

std::string s = 42; // Constructor: "equivalent" to std::string s = std::string(42)

differs from

std::string s;
s = 42; // assignation: s.operator =(42)

and std::string::operator=(char)exists, while the constructor accepting chardoes not.

+9
source

std::vector- red herring. If you just try the following, it will also compile fine:

#include <string>
int main()
{
    std::string str;
    str = 42;
}

, , std::string::operator=(char), . 42 char. ascii 42 '*'. :

#include <iostream>
#include <string>
int main()
{
    std::string str;
    str = 42;
    std::cout << str; // Prints *
}
+6

Source: https://habr.com/ru/post/1687731/


All Articles