今天在写c++程序时遇到了一个问题,声明了一个vector对象
std::vector<const std::string> str_vec;
结果程序编译报错:
此错误主要是vector中声明了const类型,此处vector<T>中的T应该是拷贝赋值的(CopyAssignable),因此不能使用const类型。
以下代码则会报上述错误
#include <iostream>
2 #include <vector>
3
4 int main(){
5 std::vector<const std::string> str_vec;
6 std::string str1 = "hello";
7 std::string str2 = "world";
8 str_vec.emplace_back(str1);
9 str_vec.emplace_back(str2);
10 for (auto item : str_vec) {
11 std::cout << item << std::endl;
12 }
13 return 0;
14 }
若改成
#include <iostream>
2 #include <vector>
3
4 int main(){
5 std::vector<std::string> str_vec;
6 std::string str1 = "hello";
7 std::string str2 = "world";
8 str_vec.emplace_back(str1);
9 str_vec.emplace_back(str2);
10 for (auto item : str_vec) {
11 std::cout << item << std::endl;
12 }
13 return 0;
14 }
则没有问题。
另外,若使用const指针是没有问题的,因为const指针是指向的对象不能改变,指针本身是可以拷贝,赋值的。即以下代码没有问题:
#include <iostream>
2 #include <vector>
3
4 int main(){
5 std::vector<const std::string*> str_vec;
6 std::string str1 = "hello";
7 std::string str2 = "world";
8 str_vec.emplace_back(&str1);
9 str_vec.emplace_back(&str2);
10 for (auto item : str_vec) {
11 std::cout << *item << std::endl;
12 }
13 return 0;
14 }
另,我是在gcc编译器下编译的,网上有说vs编译器下没有问题。

本文探讨了在C++中使用vector容器时遇到的问题,特别是关于const类型的应用限制。通过对比不同类型的vector声明方式,解释了为何不能直接将const std::string作为vector元素,并给出了正确的实现方法。

584

被折叠的 条评论
为什么被折叠?



