简体   繁体   中英

copy a vector<string> elements to other other vector<string>* (1 passing as pointer)

void check_and_fix_problems(vector<string>* fileVec, int index) {

    vector<string> q = { "something", "else", "here" };

    q.insert(q.end(), fileVec->begin() + index + 2, fileVec->end()); //add at the end of q vector the fileVec vector

    for (int f = 0; f < q.size(); f++) {//here is the problem/s
        std::copy(q.at(f).begin(), q.at(f).end(), fileVec->at(f)); //copy q vector to fileVec
        //fileVec->at(f) = q.at(f);
    }
}

i have problem with this code, when i call it i get runtime error for the fileVec vector out of range (i guess because the q vector has more elements than the fileVec so some indexes are out of range) but how i can increase the vector size of the vector via their pointer?

and also is here important to use std::copy or i can simple do the same with fileVec->at(f) = q.at(f);? (because as i know, when this function return everything in the function will deleted and the result will be all elements in fileVec showing at nullptr).

So here I tried fixing your code, though I still did not know what exactly you were doing. I assumed you need to insert another vector elements at a given index in another vector. Once you will tell the exact requirement, it can be modified accordingly :

void check_and_fix_problems(std::vector<string> &fileVec, int index) {

    std::vector<string> q = { "something", "else", "here" };

    q.insert(q.end(), fileVec.begin() + index + 2, fileVec.end()); //add at the end of q vector the fileVec vector

    //for debugging purpose
    std::cout << "q in function contains:";
    for (std::vector<string>::iterator it = q.begin() ; it < q.end(); it++)
        std::cout << ' ' << *it;
    std::cout << '\n';

    //vector<string>::iterator itr;
    // for (itr = q.begin(); itr != q.end(); itr++) {//here is the problem/s
    //     fileVec.insert(fileVec.begin() + index,*itr); //copy q vector to fileVec
    //     //fileVec->at(f) = q.at(f);
    // }
    fileVec.insert(fileVec.begin() + index, q.begin(),q.end());
}

int main ()
{
    std::vector<string> a = {"xyz","abc","says","hello"};
    check_and_fix_problems(a, 1);
    std::cout << "a contains:";
    for (std::vector<string>::iterator it = a.begin() ; it < a.end(); it++)
        std::cout << ' ' << *it;
    std::cout << '\n';
    return 0;
}

This gave the following output :

q in function contains: something else here hello
a contains: xyz something else here hello abc says hello

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