简体   繁体   中英

c++ - increasing the size of outer vector in two dimensional string vector

I am trying to develop an understanding of two dimensional string vectors (Ie a vector inside a vector) and after a few hours struggling I cannot seem to increase the size of the outer vector.

I start off by adding the following values to the first inner element {"ABC", "Abacus", "Abacus Football Club", "001"}.

I would like to then add another outer element and add "BCD" as the first value. After many failed attempts I can't increase the size of the outer vector. I present the below which I feel is the "closest" I have got to.

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

int main()
{

    vector< vector<string> > vecTeams(1, vector<string>(4)); 

    vecTeams[0][0] = "ABC";
    vecTeams[0][1] = "Abacus";
    vecTeams[0][2] = "Abacus Football Club";
    vecTeams[0][3] = "001";

    cout << vecTeams[0][1] << endl; 

    vecTeams.push_back(1); 
    vecTeams[1][0] = "BCD"; 

    cout << vecTeams[1][0] << endl;

    return 0; 
}

When trying to compile it doesn't like:

vecTeams.push_back(1); 

What is it that I am misunderstanding and how can I increase the size of the vector and thus continue to add data?

Many thanks,

José

Since vecTeams is a container that contains std::vector<std::string> s, then, logically, that's what you need to add to it:

vecTeams.push_back(std::vector<std::string>()); 

push_back() 's parameter is the new value to add to the end of the container, and not the number of new values to add to the container. Since the container contains std::vector<std::string> s, you have to construct a new one, and push it back.

You can also use resize() to accomplish the same thing:

vecTeams.resize(2);

Now, there are two elements in the container.

The argument to push_back is a vector to push. 1 is not a vector.

You could use:

vecTeams.push_back( vector<string>(4) );

or perhaps:

vecTeams.resize(2);
vecTeams[1].resize(4);

Alternatively you could create each row before pushing it:

vector< vector<string> > vecTeams;
vector<string> team;

team = { "ABC", "Abacus", "Abacus Football Club", "001" };
vecTeams.push_back(team);

team = { "BCD", "bla", "bla", "002" };
vecTeams.push_back(team);

In fact you don't even need team in this code, you can put the braced list directly in the push_back call.

If every row is going to have 4 strings in it, consider using std::array<string, 4> as the row type, or a struct .

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