我已经生成了一个二维vector,但是我需要在后来给里面的每一个vector添加一个数据,下面是我写的代码,可是数据并没有添加到vector里来.
std::vector <std::vector<std::string>> array;
std::vector <std::string> x,y;
x.push_back("3");
x.push_back("null");
x.push_back("1");
x.push_back("2");
x.push_back("1");
x.push_back("2");
y.push_back("4");
y.push_back("aaa");
y.push_back("2");
y.push_back("3");
y.push_back("11");
y.push_back("1");
array.push_back(x);
array.push_back(y);
for(auto a : array)
{
a.push_back("xxxx");
}
for(auto a : array)
{
for(auto b : a)
{
std::cout << b << " ";
}
std::cout << std::endl;
}
输出的是:
3 null 1 2 1 2
4 aaa 2 3 11 1
c++ vector内部对存放的内容并不是用指针进行引用的,所以:
for(auto a : array) // 取出来的a其实是相当于复制了一份出来
{
a.push_back("xxxx"); // 所做的操作仅仅是对复制的东西进行操作,而不是对存在array里面的vector进行操作
}
改成用指针实现就可以了
#include "iostream"
#include "string"
#include "vector"
using namespace std;
int main()
{
vector <vector<string>* > array;
vector <string> *x = new vector<string>(),*y = new vector<string>();
x->push_back("3");
x->push_back("null");
x->push_back("1");
x->push_back("2");
x->push_back("1");
x->push_back("2");
y->push_back("4");
y->push_back("aaa");
y->push_back("2");
y->push_back("3");
y->push_back("11");
y->push_back("1");
array.push_back(x);
array.push_back(y);
for(auto a : array)
{
a->push_back("xxxx");
}
for(auto a : array)
{
for(auto b : *a)
{
cout << b << " ";
}
cout << endl;
}
return 0;
}