开发者

copying arrays of strings in C++

I have an array of variables of type string. Something like:

std::string Array1[3] = {"A","B","C"}; 

I would like to copy the contents of this array into another one:

std::string Array2[3]; 

At the moment I use a loop to do this. Is there any simpler/alternative way? Also if I declare and initialise 开发者_高级运维the variable as follows:

if( ... check some condition ... ) 
{
    .
    .
    std::string Array1[3] = {"A","B","C"}; 
}  

it will obviously be destroyed once leaving the scope of the if statement. Is there a way of avoiding this so that it can be used later in the function. Ideally I would like to avoid declaring the variable Array1 global.

Thanks


No, with an array of complex objects you need a loop, or you can wrap the loop with std::copy:

std::string Array1[3] = { "A", "B", "C" };
std::string Array2[3];
std::copy(Array1, Array1 + 3, Array2);

However, I suggest using the more canonical std::vector, which has native assignment (see this SO answer for the ways to populate a std::vector):

std::vector<std::string> Array1, Array2;
Array1.push_back("A"); Array1.push_back("B"); Array1.push_back("C");
Array2 = Array1;

Or, at the very least, boost::array (std::array if you're on C++0x, std::tr1:array or similar on TR1-capable toolchains like recent MSVS), which is a statically-allocated equivalent that can also be assigned:

using boost::array; // swap as appropriate
array<std::string, 3> Array1 = {{ "A", "B", "C" }}; // yes, I used two
array<std::string, 3> Array2 = Array1;


You can use std::copy (and most algorithms) with pointers, and the arrays easily decay into pointers, so you can do something like this to avoid unrolling your own loop (ensuring that the sizes are correct):

std::string src[3] = { "A", "B", "C" };
std::string dst[3];
std::copy( src, src + 3, dst );

On the second part of the question I don't quite grasp what you want to do. Either the array is local to the scope or not, if it is local to the scope you cannot use it outside of that scope, if you need it at function scope, just declare it there.


Try using std::vector also:

std::string strs[3] = {"A","B","C"};  //from your code!

std::vector<std::string> strvector(strs, strs+3); //improvement!

Or,

std::vector<std::string> strvector; //declare 

//later on!
std::copy(strs, strs+3, std::back_inserter(strvector)); //improvement!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜