C++ 中 std::vector存储const型对象报错

今天在写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编译器下没有问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值