Priyatham Priyatham - 3 months ago 15
C++ Question

Why doesn't std::transform convert the std::string vector to unsigned int vector?

As described in the title, I am trying to convert a vector of

std::string
to
unsigned int
. But I am getting a segmentation fault. Here's my code:

#include<iostream>
#include<string>
#include<vector>
#include<sstream>

int main() {
unsigned int N = 3;
std::string array_string = "2 5 8";
std::vector<unsigned int> A;

std::istringstream array_stream(array_string);

std::vector<std::string> array {
std::istream_iterator<std::string>{array_stream},
std::istream_iterator<std::string>{}
};
A.clear(); A.reserve(N);
std::transform(array.begin(), array.end(), A.begin(), [] (const std::string& str) {
return std::stoi(str);
});
for(std::vector<unsigned int>::iterator it = A.begin(); it != A.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
std::cout << A.size() << std::endl;
return 0;
}


OTOH, changing
A.begin()
to
std::back_inserter(A)
in the call to
std::transform
works. Is this because
A.begin()
fails when
A
is empty?

Answer

Is this because A.begin() fails when A is empty?

Yes, that's why. Your call to reserve doesn't change the fact that A is empty, it is still empty afterwards. Calling reserve only changes the capacity, i.e. subsequent insertions will not allocate any memory.

If you want to use A.begin(), you have to call resize, as that will actually change the size of A:

A.resize(N); //Resize array
std::transform(array.begin(), array.end(), A.begin(), [] (const std::string& str) {
    return std::stoi(str);
});