Search code examples
c++vectorpush-backsplit

Vector Push_back


Possible Duplicate:
Empty check with string split

I split the below string with '&' and saved it in a vector

const vector<string> vec = split("f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=","&");

Now i'm again splitting the split strings with '=' Using the below code.

vector<string> vec1;
for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
{
     vec1=split(vec.at(a),"=");

}

At last I'm getting only the last item of the vector 'vec' to 'vec1'. every time my vec1 pointer refreshing. But i want to add splitted string in last position of the vec1. How can i do this ?


Solution

  • You assign to vec1 every time in the loop, so it will only contain the last pair. Instead you should append to vec1. This is done simplest with the insert function:

    vector<string> vec1;
    for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
    {
        vector<string> tmp = split(vec.at(a),"=");
        vec1.insert(vec1.end(), tmp.begin(), tmp.end());
    }