Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is correct: vector<const string> OR const vector<string>?

Tags:

c++

vector

Which is correct: vector<const string> OR const vector<string>?

I want to create an std::vector of std::strings, and I won't make changes to it. But I am not sure which of the two ways is better and why.

like image 470
user3111311 Avatar asked Jan 26 '14 15:01

user3111311


People also ask

What is a const vector in C++?

A const vector will return a const reference to its elements via the [] operator . In the first case, you cannot change the value of a const int&. In the second case, you cannot change the value of a reference to a constant pointer, but you can change the value the pointer is pointed to.

Can you modify const vector in C++?

const vector<string>: Cannot change anything about the vector.

Can you add to a const vector?

You can't put items into a const vector, the vectors state is the items it holds, and adding items to the vector modifies that state. If you want to append to a vector you must take in a non const ref. Show activity on this post. If you have a const vector it means you can only read the elements from that vector.


1 Answers

If your only choices are those two and you want the program to compile, use const std::vector<std::string>.

If you don't mind compilation errors (both on GCC4.8 and Clang), probably due to the fact that const std::string does not meet the requirement of CopyAssignable (prior to C++11) or MoveAssignable (since C++11), even though, apparently, it's mostly because it's not Destructible, use std::vector<const std::string>.

like image 126
Shoe Avatar answered Oct 21 '22 04:10

Shoe