0

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

1
  • Find out what regular the strings are, then generate strings by function. Commented Apr 1, 2014 at 6:47

2 Answers 2

5

First, drop the pointers and new1. 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++.

Sign up to request clarification or add additional context in comments.

5 Comments

@user63898 Because there is no reason to use it. And by using new you were just buying yourself a memory management problem.
but what is i like to pass the vector into other methods ?
@user63898 It is fine. If you don't want to make a copy, you pass a reference. But that has nothing to do with using new.
so when should i make new ?
@user63898 For example, when implementing a container (if you ever have to.) Currently, you still need to call new to instantiate a unique_ptr, but there is a make_unique function out there that lets you avoid this. It will be part of the next C++ standard. The point is that the standard library gives you many types and tools that allow you to avoid having to deal with new and delete directly.
1
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

1 Comment

Can you be more clear? This is not the telegraph office.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.