简体   繁体   中英

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

i have configuration that i need to set into some kind of container i try to set into std::vector but im getting compilation errors in both ways:

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

    ConfigVec->at(1) = "11111\
             00000\
            00000";

what is the shortst way to do that without to many std::string declarations

First, drop the pointers and new 1 . Second, you are appending to elements that don't exist. Push strings back into the vector.

std::vector<std::string> ConfigVec;

ConfigVec.push_back("000001111100000");
ConfigVec.push_back("111110000000000");

and so on.

If you have a small number of strings, you can initialize the vector directly (unless you're stuck with a pre-C++11 implementation):

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

1 * You were using ConfigVec as a pointer (assigning the result of new to it, and using -> to access its members), but it isn't actually declared as one. This in itself is an error. In any case, there is little case for using new and raw pointers to dynamically allocated resources in C++.

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

This is "java-nese": std::vector<std::string> ConfigVec is just a vectcor of string itself. ConfigVect.push_back("text") will just add a string at the end.

Or did you mean

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

In any case you cannot use at (or [] ) on an empty vector, unlsess you first size it appropriately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM