copying arrays of strings in C++

11,625

Solution 1

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;

Solution 2

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.

Share:
11,625
Wawel100
Author by

Wawel100

Quantitative Developer/Mathematican based in Poland

Updated on June 28, 2022

Comments

  • Wawel100
    Wawel100 almost 2 years

    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

  • Collin Dauphinee
    Collin Dauphinee about 13 years
    I'm pretty sure std::array is in tr1. Visual Studio has it included in tr1, at least.
  • Lightness Races in Orbit
    Lightness Races in Orbit about 13 years
    @dauphic: As std::tr1::array, yes. Though precise namespaceness varies across implementations.
  • Lightness Races in Orbit
    Lightness Races in Orbit about 13 years
  • Lightness Races in Orbit
    Lightness Races in Orbit about 13 years
    Unable to comply, attempted division by zero