[英]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
. 如标题中所述,我正在尝试将
std::string
的向量转换为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. OTOH,在对
std::transform
的调用A.begin()
更改为std::back_inserter(A)
。 Is this because A.begin()
fails when A
is empty? 这是因为
A
为空时A.begin()
失败了吗?
Is this because
A.begin()
fails whenA
is empty?这是因为
A
为空时A.begin()
失败了吗?
Yes, that's why. 是的,这就是原因。 Your call to
reserve
doesn't change the fact that A
is empty, it is still empty afterwards. 您的
reserve
电话不会改变A
为空的事实,此后它仍然为空。 Calling reserve
only changes the capacity , ie subsequent insertions will not allocate any memory. 调用
reserve
仅更改容量 ,即后续插入将不会分配任何内存。
If you want to use A.begin()
, you have to call resize
, as that will actually change the size of A
: 如果要使用
A.begin()
,则必须调用resize
,因为这实际上会更改A
的大小:
A.resize(N); //Resize array
std::transform(array.begin(), array.end(), A.begin(), [] (const std::string& str) {
return std::stoi(str);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.