簡體   English   中英

如何創建一個正常運行的向量<wchar_t>有一個擦除(size_t pos)方法?</wchar_t>

[英]how do I create a functioning vector<wchar_t> that has an erase(size_t pos) method?

我正在創建一個 C++ wstring class 用於 mingw 版本 4.3.0,用於 Win32 的交叉編譯。 我希望我的字符串像std::string一樣工作,這意味着我想要一個擦除 position pos處的單個元素的erase(int pos)方法。

這是我的第一次嘗試:

#include <wchar.h>
#include <iostream>
#include <vector>

class wstring : public std::vector<wchar_t>{
public:
    void erase(size_t where){
    erase(begin()+where);
    }
};

int main(int argc,char **argv) {
    wstring c1;
    c1.push_back(L'a');
    c1.push_back(L'b');
    c1.push_back(L'c');
    c1.erase(1);

    for(size_t i = 0;i<c1.size();i++){
    std::cout << "c1[" << i << "] = " << c1[i] << "\n";
    }
    return 0;
}

這看起來應該對我有用,但是當我嘗試編譯它時,我得到了這個 wacko 編譯器錯誤:

$ i386-mingw32-g++ x1.cpp
x1.cpp: In member function 'void wstring::erase(size_t)':
x1.cpp:8: error: no matching function for call to 'wstring::erase(__gnu_cxx::__normal_iterator<wchar_t*, std::vector<wchar_t, std::allocator<wchar_t> > >)'
x1.cpp:7: note: candidates are: void wstring::erase(size_t)
$ 

真正奇怪的是,如果我取出erase方法,只是內聯代碼,我沒有問題:

#include <wchar.h>
#include <iostream>
#include <vector>

class wstring : public std::vector<wchar_t>{
};

int main(int argc,char **argv) {
    wstring c1;
    c1.push_back(L'a');
    c1.push_back(L'b');
    c1.push_back(L'c');
    c1.erase(c1.begin()+1);

    for(size_t i = 0;i<c1.size();i++){
    std::cout << "c1[" << i << "] = " << c1[i] << "\n";
    }
    return 0;
}

我很迷惑。

您的特定問題的答案是使用std::vector<T>::erase( iterator )而不是remove

std::vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
v.erase( v.begin()+1 ); // equivalent to v.remove( 1 )

但我不認為你在正確的樹上吠叫。 標准庫中已經有一個std::wstringbasic_stringwchar_t的實例化,它將盡可能接近std::string (這是與char相同模板的實例化)

您總是可以只使用現有類型std::wstring ,它是std::basic_string<wchar_t>的 typedef。 也可以根據您最喜歡的整數類型隨意創建其他字符串類。

請注意,有相應的 stream 對象std::wcout等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM