[英]how do I create a functioning vector<wchar_t> that has an erase(size_t pos) method?
I am creating a C++ wstring
class for use with mingw version 4.3.0, cross-compiling for Win32.我正在创建一个 C++
wstring
class 用于 mingw 版本 4.3.0,用于 Win32 的交叉编译。 I want my string to work like std::string
which means that I want an erase(int pos)
method that erases a single element at position pos
.我希望我的字符串像
std::string
一样工作,这意味着我想要一个擦除 position pos
处的单个元素的erase(int pos)
方法。
Here is my first attempt:这是我的第一次尝试:
#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;
}
This looks like it should work to me, but I get this wacko compiler error when I try to compile it:这看起来应该对我有用,但是当我尝试编译它时,我得到了这个 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)
$
What's really weird is that if I take out the erase
method and just inline the code, I have no problem:真正奇怪的是,如果我取出
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;
}
I'm mystified.我很迷惑。
The answer to your particular question is to use std::vector<T>::erase( iterator )
instead of remove
:您的特定问题的答案是使用
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 )
But I don't think that you are barking at the right tree.但我不认为你在正确的树上吠叫。 There is already a
std::wstring
in the standard library that is the instantiation of basic_string
with wchar_t
, and that will get as close as it can to std::string
(which is an instantiation of the same template with char
)标准库中已经有一个
std::wstring
是basic_string
与wchar_t
的实例化,它将尽可能接近std::string
(这是与char
相同模板的实例化)
You could always just use the existing type std::wstring
, which is a typedef for std::basic_string<wchar_t>
.您总是可以只使用现有类型
std::wstring
,它是std::basic_string<wchar_t>
的 typedef。 Feel free to make other string classes based on your favourite integral types, too.也可以根据您最喜欢的整数类型随意创建其他字符串类。
Note that there are corresponding stream objects std::wcout
etc.请注意,有相应的 stream 对象
std::wcout
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.