如何设置std::vector<std::string>每个元素中的自定义字符串

How to set std::vector<std::string> with custom string in each element

本文关键字:std 元素 字符串 自定义 gt lt 何设置 设置 vector string      更新时间:2023-10-16

>我需要将配置设置到某种容器中我尝试设置标准::矢量但是我以两种方式收到编译错误:

 std::vector<std::string> ConfigVec= new std::vector<std::string>();
  ConfigVec->at(0).append("00000
              11111
               00000");
    ConfigVec->at(1) = "11111
             00000
            00000";

没有很多 std::string 声明的最短方法是什么

首先,删除指针并new 1。其次,你正在追加到不存在的元素。将字符串推回矢量。

std::vector<std::string> ConfigVec;
ConfigVec.push_back("000001111100000");
ConfigVec.push_back("111110000000000");

等等。

如果你有少量字符串,你可以直接初始化向量(除非你坚持使用 C++11 之前的实现):

std::vector<std::string> ConfigVec{"000001111100000", "111110000000000"};

1 * 您使用 ConfigVec 作为指针(将new的结果分配给它,并使用 -> 访问其成员),但它实际上并未声明为指针。这本身就是一个错误。无论如何,很少有理由使用 new 和原始指针来动态分配C++资源。

std::vector<std::string> ConfigVec= new std::vector<std::string>();

这是"java-nese":std::vector<std::string> ConfigVec只是字符串本身的vectcor。 ConfigVect.push_back("text")只会在末尾添加一个字符串。

还是你的意思

std::vector<std::string>* ConfigVec= new std::vector<std::string>();
//----------------------^-----------<< note taht!

在任何情况下,您都不能在空向量上使用at(或[]),请首先适当调整其大小