vector <bool>的替代方案正如(希望)我們都知道的那樣,vector<bool>完全被打破并且不能被視為C數(shù)組。獲得此功能的最佳方法是什么?到目前為止,我所想到的想法是:使用vector<char>替代,或使用包裝類并擁有 vector<bool_wrapper>你們怎么處理這個問題?我需要這個c_array()功能。作為一個附帶問題,如果我不需要該c_array()方法,如果我需要隨機(jī)訪問,那么解決此問題的最佳方法是什么?我應(yīng)該使用雙端隊列還是別的什么?編輯:我確實需要動態(tài)調(diào)整大小。對于那些不知道的人,vector<bool>是專門的,每個人bool需要1位。因此,您無法將其轉(zhuǎn)換為C風(fēng)格的數(shù)組。我猜“包裝”有點用詞不當(dāng)。我在想這樣的事情:當(dāng)然,然后我必須閱讀my_bool由于可能的對齊問題:(struct my_bool{
bool the_bool;};vector<my_bool> haha_i_tricked_you;
3 回答

郎朗坤
TA貢獻(xiàn)1921條經(jīng)驗 獲得超9個贊

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗 獲得超6個贊
這是一個有趣的問題。
如果你需要一個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;}
我用VC9試過這個,看起來效果很好。Bool類的想法是通過提供相同的行為和大小(但不是相同的類型)來模擬bool類型。幾乎所有的工作都是由bool操作符和默認(rèn)的復(fù)制構(gòu)造函數(shù)完成的。我添加了一個排序,以確保它在使用算法時作出假設(shè)。
不確定它是否適合所有情況。如果它適合您的需求,那么重寫類似矢量的類就不那么重要了......

ABOUTYOU
TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
取決于您的需求。我也會去std::vector<unsigned char>
。如果你只使用功能的一個子集,寫一個包裝器就可以了,否則它將成為一場噩夢。
- 3 回答
- 0 關(guān)注
- 1093 瀏覽
添加回答
舉報
0/150
提交
取消