【发布时间】:2018-08-18 09:37:34
【问题描述】:
如果为 32 位 Linux 系统编译下面的代码会返回错误的结果,同样的问题也适用于 64 位系统,给定足够大的向量。
是否违反了 lower_bound 或 STL 的先决条件,如果有,在哪里?
STL 消息来源告诉我,向量的大小被转换为有符号类型,这解释了这种行为。
// compile with and without -m32 switch
#include<algorithm>
#include<iostream>
#include<stdexcept>
#include<vector>
using namespace std;
int main() {
try {
vector<uint8_t> v((1ULL << 28) * 9, 2); // 2.25 G entries
v.back() = 3; // the last of which is greater
cout<< "Vector maximal size: "<<v.max_size()<< " and actual size: " << v.size() <<endl;
uint8_t val=3;
auto x= lower_bound(v.begin(), v.end(), val );
if (x!=v.end() && !( val< *x ) ) {
cout << "Found value " << int(*x) << endl;
} else {
cout << "Not Found " << endl;
}
} catch (exception const & ex){
cerr<< ex.what()<<endl;
}
}
输出:(Linux 操作系统和 Clang++ 7.0.0)
向量最大大小:4294967295 实际大小:2415919104 发现值 2
输出:(Windows 10 操作系统和 32 位 msvc)
向量太长了
更新:虽然正在修复 std::vector,但问题仍然存在于分配的数组中
自动 p= 新 uint8_t[sz]; // 2.25 G 条目
结果取决于编译器和标准库。
【问题讨论】:
-
v.size() > v.max_size()在你的编译中吗? -
不,Linux max_size()=4G 太大,微软 STL 是对的。它会抛出 bad_alloc 吗?
-
它抛出
std::length_error([vector.capacity],reserve(): Throws:length_errorifn > max_size())。
标签: c++ linux stl c++17 stl-algorithm