std::sort 输入向量已调用保留时无法工作
std::sort fail to work when input vector has called reserve
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(-1.0, 1.0);
std::vector<float> s;
s.reserve(10);
for (int i=0; i< 10; ++i) s[i] = dis(gen);
for (int i=0; i< 10; ++i) std::cout << s[i] << " ";
std::cout << std::endl;
std::sort(s.begin(), s.end());
for (int i=0; i< 10; ++i) std::cout << s[i] << " ";
std::cout << std::endl;
}
输出是:
0.459711 0.0240773 -0.395009 0.574655 -0.244166 -0.343489 -0.520125 0.746452 0.858716 0.765223
0.459711 0.0240773 -0.395009 0.574655 -0.244166 -0.343489 -0.520125 0.746452 0.858716 0.765223
std::sort 失败!!!
.reserve
不会调整向量的大小,因此 s[i]
是未定义的行为。您必须改用 .resize
或使用 push_back
来插入元素。
在 .reserve
之后 .begin()
仍然等于 .end()
(如在空向量中),这意味着 std::sort
将没有任何效果。
reserve
不会自动将矢量内部大小设置为您指定的大小。它所做的只是将其内部数组的容量更改为 10,而其大小保持不变。
在 i
大于或等于向量的大小时调用 s[i]
将产生未定义的行为。
要解决此问题,请更改
s[i] = dis(gen);
到
s.push_back(dis(gen));
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(-1.0, 1.0);
std::vector<float> s;
s.reserve(10);
for (int i=0; i< 10; ++i) s[i] = dis(gen);
for (int i=0; i< 10; ++i) std::cout << s[i] << " ";
std::cout << std::endl;
std::sort(s.begin(), s.end());
for (int i=0; i< 10; ++i) std::cout << s[i] << " ";
std::cout << std::endl;
}
输出是: 0.459711 0.0240773 -0.395009 0.574655 -0.244166 -0.343489 -0.520125 0.746452 0.858716 0.765223 0.459711 0.0240773 -0.395009 0.574655 -0.244166 -0.343489 -0.520125 0.746452 0.858716 0.765223 std::sort 失败!!!
.reserve
不会调整向量的大小,因此 s[i]
是未定义的行为。您必须改用 .resize
或使用 push_back
来插入元素。
在 .reserve
之后 .begin()
仍然等于 .end()
(如在空向量中),这意味着 std::sort
将没有任何效果。
reserve
不会自动将矢量内部大小设置为您指定的大小。它所做的只是将其内部数组的容量更改为 10,而其大小保持不变。
在 i
大于或等于向量的大小时调用 s[i]
将产生未定义的行为。
要解决此问题,请更改
s[i] = dis(gen);
到
s.push_back(dis(gen));