I am creating a C++ wstring
class for use with mingw version 4.3.0, cross-compiling for 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
.
Here is my first attempt:
#include <wchar.h>
#include <iostream>
#include <vector>
class wstring : public std::vector<wchar_t>{
public:
void erase(size_t whe开发者_开发百科re){
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:
$ 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:
#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<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
)
You could always just use the existing type std::wstring
, which is a typedef for std::basic_string<wchar_t>
. Feel free to make other string classes based on your favourite integral types, too.
Note that there are corresponding stream objects std::wcout
etc.
精彩评论