This will compile:
std::vector<std::string> test{"hello"}
std::cout << tt.[0] << '\n';
tt[0].append(" world");
std::cout << tt.[0] << '\n';
Output:
hello
hello world
This will not:
const std::vector<std::string> test{"hello"}
std::cout << tt.[0] << '\n';
tt[0].append(" world");
std::cout << tt.[0] << '\n';
More importantly, as expected, this will not compile:
std::vector<const std::string> test{"hello"}
std::cout << tt.[0] << '\n';
tt[0].append(" world");
std::cout << tt.[0] << '\n';
but sadly, neither will this:
std::vector<std::string> test{"hello"}
std::cout << tt.[0] << '\n';
There are many differing answers to questions about immutability of std::vector and details on cppreference.com (Assignable, CopyAssignable...). But getting down to what I'd like to be able to do (so the question is: "how do I do this..."? --
- define a std::vectorstd::string that will allow me to ensure the elements, once added, cannot be changed -- but the vector can be changed, including adding new and deleting existing elements and changing their order (std::vector failed though seemed a reasonable approach without understanding the details of std::vector)
- define a std::vectorstd::string that will not allow me to change the vector or its elements (const std::vectorstd::string seems to work)
- define a std::vectorstd::string that allows the existing elements to be modified but the vector itself will always have the same number and order of elements (this is not particularly interesting to me)
- std::vectorstd::string is fully modifiable.
Aucun commentaire:
Enregistrer un commentaire