简体   繁体   中英

Insert vector into another vector

Can I do something like this?

std::vector<std::vector<std::string>> vec;

vec.push_back(std::vector<std::string>("abc", "cde", "fgh", "ijk"));
vec.push_back(std::vector<std::string>("abc", "cde", "fgh", "ijk"));
vec.push_back(std::vector<std::string>("abc", "cde", "fgh", "ijk"));

I already know which values I want and I'm trying to create a 3 x 4 vector like this.

Edit: I would also prefer a C++03 solution since my compiler doesn't support C++11.

You need to use :

vec.push_back(std::vector<std::string>( { "abc", "cde", "fgh", "ijk" } ) ) ;
                                        ~~                          ~~

I already know which values

Then why not this ? (C++11)

std::vector<std::vector<std::string>> vec 
{
{ "abc", "cde", "fgh", "ijk" },
{ "abc", "cde", "fgh", "ijk" },
{ "abc", "cde", "fgh", "ijk" },
} ;

For repeating vectors of strings, you can use another constructor overload taking a count and the repeated element:

#include <iostream>
#include <string>
#include <vector>

int main ()
{

    std::vector<std::vector<std::string>> vec 
    (
        3, { "abc", "cde", "fgh", "ijk" }
    );

    for (v : vec) {
        for (s : v)
            std::cout << s << ",";
        std::cout << "\n";
    }
}

Live Example

You can have vector of vectors, but you initialize them wrongly. There is no constructor that accepts 4 parameters of type T. You can however make them an initialization list since c++11.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    std::vector<std::vector<std::string>> vec;
    vec.push_back(std::vector<std::string>({"abc", "cde", "fgh", "ijk"}));
    vec.push_back(std::vector<std::string>({"abc", "cde", "fgh", "ijk"}));
    vec.push_back(std::vector<std::string>({"abc", "cde", "fgh", "ijk"}));
    return 0;
}

Another one (even for prior to C++11):

int main() {
    std::vector<std::vector<std::string> > vec;
    std::string aa[] = {"abc", "cde", "fgh", "ijk"};
    std::vector<std::string> vec1(aa, aa+sizeof(aa)/sizeof(std::string));

    vec.push_back(vec1);
    vec.push_back(vec1);
    vec.push_back(vec1);
    return 0;
}

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