Storing strings in an array into a vector

How can you store a string into a vector from an array of strings? For example,
I have an array (string myarray[3][4]) and a vector<string> myVector. I figure the push_back method could work, like this myVector.push_back(myarray[i][j]+", "+myarray[i][j+1]+","+myarray[i][j+2]+","+myarray[i][j+3]), but it doesn't seem to give me a favorable result. How could I make it so that the entire array is stored into the vector?
Last edited on
If you want a single dimensioned vector to hold the multiple dimensioned array you probably will need to use a couple of loops.

1
2
3
4
5
6
7
8
std::string myArray[3][4];  // Should use named constants instead of the magic numbers (3,4).

std::vector<std::string> myVector;

for(size_t i = 0; i < 3; ++i) // See the note above.
   for(size_t j = 0; j < 4; ++j) // See the note above.
      myVector.push_back(myArray[i][j]);


There are probably many other ways as well, but probably the best way would be to try to use the std::vector instead of the array in the first place.

Consider moving instead of copying if the array elements are not required after the operation and can be left in a stable but undefined state:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <iterator>

constexpr auto ROW = 3;
constexpr auto COL = 4;

int  main()
{
    std::string myArray[ROW][COL] = {{"one", "two", "three", "four"}, {"five", "six", "seven", "eight"},
                                {"nine", "ten", "eleven", "twelve"}};
    std::vector<std::string> myVector{};

    for (auto i = 0; i < ROW; ++i)
    {
        std::move(std::begin(myArray[i]), std::end(myArray[i]), std::back_inserter(myVector));
        //http://stackoverflow.com/questions/15004517/moving-elements-from-stdvector-to-another-one
    }
    for (const auto& elem : myVector)std::cout << elem << " "; std::cout << "\n";

    for (auto i = 0; i < ROW; ++i)
    {
        for (auto j = 0; j < COL; ++j)
        {
            std::cout << myArray[i][j] << " ";//prints blanks
        }
        std::cout << "\n";
    }
}
Topic archived. No new replies allowed.