rlb*_*ond 86 c++ stl boolean vector
正如(希望)我们都知道的那样,vector<bool>完全被打破,不能被视为交流阵列.获得此功能的最佳方法是什么?到目前为止,我所想到的想法是:
vector<char>替代,或vector<bool_wrapper>你们怎么处理这个问题?我需要c_array()功能.
作为一个附带问题,如果我不需要c_array()方法,如果我需要随机访问,解决此问题的最佳方法是什么?我应该使用双端队列还是别的什么?
编辑:
c_array()是专门的,所以每个bool需要1位.因此,您无法将其转换为C风格的数组.当然,由于可能的对齐问题,我必须读入my_bool :(
struct my_bool
{
bool the_bool;
};
vector<my_bool> haha_i_tricked_you;
Run Code Online (Sandbox Code Playgroud)
Kla*_*aim 20
这是一个有趣的问题.
如果你需要一个std :: vector,如果它不是专门的,那么也许这样的东西可以适用于你的情况:
#include <vector>
#include <iostream>
#include <algorithm>
class Bool
{
public:
Bool(): m_value(){}
Bool( bool value ) : m_value(value){}
operator bool() const { return m_value;}
// the following operators are to allow bool* b = &v[0]; (v is a vector here).
bool* operator& () { return &m_value; }
const bool * const operator& () const { return &m_value; }
private:
bool m_value;
};
int main()
{
std::vector<Bool> working_solution(10, false);
working_solution[5] = true;
working_solution[7] = true;
for( int i = 0; i < working_solution.size(); ++i )
{
std::cout<< "Id " << i << " = " << working_solution[i] << "(" <<(working_solution[i] ? "true" : "false") << ")" <<std::endl; // i used ? : to be sure the boolean evaluation is correct
}
std::sort( working_solution.begin(), working_solution.end());
std::cout<< "--- SORTED! ---" << std::endl;
for( int i = 0; i < working_solution.size(); ++i )
{
bool* b = &working_solution[i]; // this works!
std::cout<< "Id " << i << " = " << working_solution[i] << "(" << (working_solution[i] ? "true" : "false") << ")" <<std::endl; // i used ? : to be sure the boolean evaluation is correct
}
std::cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我用VC9试过这个,看起来效果很好.Bool类的想法是通过提供相同的行为和大小(但不是相同的类型)来模拟bool类型.几乎所有的工作都是由bool操作符和默认的复制构造函数完成的.我添加了一个排序,以确保它在使用算法时作出假设.
不确定它是否适合所有情况.如果它适合您的需求,那么重写类似矢量的类就不那么重要了......
Dav*_*eas 17
取决于您的需求.我也会去std::vector<unsigned char>.如果你只使用功能的一个子集,写一个包装器就可以了,否则它将成为一场噩梦.
Evg*_*yuk 12
你们怎么处理这个问题?我需要c_array()功能.
boost::container::vector<bool>:
vector < bool > specialization一直存在很大的问题,并且已经有几次尝试不推荐使用或从标准中删除它.
Boost.Container没有实现它,因为有一个优秀的Boost.DynamicBitset解决方案....
因此boost :: container :: vector :: iterator返回真正的bool引用,并作为完全兼容的容器.如果您需要内存优化版本的boost :: container :: vector < bool >功能,请使用Boost.DynamicBitset.
这个问题已经在 comp.lang.c++.moderated 上讨论过。建议的解决方案:
std::allocator)和自己的向量专业化;std::deque(正如 S. Mayers 的一本书中所推荐的那样)-但这不符合您的要求;bool包装纸; char/ /等)来代替; intboolbool另外,我很早就看到了标准委员会的提案 - 引入宏(类似的东西STD_VECTOR_BOOL_SPECIAL)来禁止这种专业化 - 但据我所知,这个提案没有在 stl 实现中实现,也没有被批准。
看来你的问题没有办法很好地做到这一点......也许在 C++0x 中。
考虑使用vector <int>.一旦你通过编译和类型检查,bool和int都只是机器字(编辑:显然这并不总是正确;但在许多PC架构上都是如此).如果您想在没有警告的情况下进行转换,请使用"bool foo = !! bar",它将零转换为false,将非零转换为true.
vector <char>或类似的将使用更少的空间,但它也有可能在某些情况下(非常小的)速度命中,因为字符小于机器字大小.我认为,这是使用int而不是chars实现bool的主要原因.
如果你真的想要干净的语义,我也喜欢制作你自己的布尔类的建议 - 看起来像一个bool,就像一个bool,但是愚弄模板专业化.
此外,欢迎来自那些希望从C++标准中删除vector <bool>专业化的人员(使用bit_vector替换它)的俱乐部.这是所有酷孩子们出去玩的地方:).
| 归档时间: |
|
| 查看次数: |
36268 次 |
| 最近记录: |