简体   繁体   中英

Copying elements from a char vector to a string vector

I have a vector of chars and I want to copy the elements in a string vector.I want each cell of the second vector to have k elements of the first, forming a string. Although I have no compiling errors the programm crashes when it forms the string vector.

Thanks in advance!

vector<string> v2;

for(int i = 0; i <= v1.size(); i++){    //v1 is the char vector

    for(int j = 0; j <= k; j++){
        v2[i] = v2[i] + v1[j];
    }

    cout << v2[i] << endl;
}

Your vector v2 is empty when you access v2[i] : this operation is, thus, illegal. You probably want something like

std::vector<std::string> v2;
v2.reserve(v1.size()); // optionally reserve enough elements; may improve performance
for (std::string::const_iterator it(v1.begin()), end(v1.end()); it != end; ++it) {
    v2.push_back(std::string(it, it + std::min(k, std::distance(it, end))));
    std::cout << v2.back() << '\n';
}

You had to make sure that your other vector has enough elements in it.

(UPDATE: using postfix operation for v2 will save memory and running time, because in that case no temporary variable has to be allocated to perform the addition operation.)

vector <string> v2(v1.size());
for(int i=0;i<=v1.size();i++){    //v1 is the char vector
    for (int j=0;j<=k;j++){
        v2[i]+=v1[j];
    }
cout<<v2[i]<<endl;
}

There's a string constructor that takes a pair of iterators -- use it to grab k consecutive characters. Then, start the next string where the last one ended (I think this is what your question meant?)

vector<string> v2;

auto p1 = v1.begin();
auto const pend = v1.end();
if (v1.size() > k) {
    auto const pendk = pend - k;
    do {
        auto const p2 = p1 + k; // locate k characters
        v2.emplace_back(p1, p2);// make a string from those characters
        p1 = p2;                // the end of this one is the start of the next
    } while (p1 < pendk);
}
if (p1 != pend)             // deal with any leftover (<= k) characters at the end
    v2.emplace_back(p1, pend);

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