C++ 转换向量<;char>;将字符*和字符串设置为常量
如何将向量转换为常量字符*?还要串吗? 这合法吗C++ 转换向量<;char>;将字符*和字符串设置为常量,c++,string,iterator,char,stdvector,C++,String,Iterator,Char,Stdvector,如何将向量转换为常量字符*?还要串吗? 这合法吗 void Printer::Wrap(const CharVector& text, RangeVector& result) const //if (TestLineWidth(text.begin(), text.end())) int c = 0; for (CharVector::const_iterator it = text.begin(); it != text.end(); ++it)
void Printer::Wrap(const CharVector& text, RangeVector& result) const
//if (TestLineWidth(text.begin(), text.end()))
int c = 0;
for (CharVector::const_iterator it = text.begin(); it != text.end(); ++it)
c++;
if (TestLineWidth(&text[0], &text[c]))
以下是CharVector和TestLineWidth的声明:
typedef std::vector<char> CharVector;
bool TestLineWidth(const char* from, const char* to) const;
typedef std::vector CharVector;
bool TestLineWidth(const char*from,const char*to)const;
#包括
#包括
#包括
使用名称空间std;
int main(){
向量数据={'h','e','l','l','o','!'};
cout如果您想将字符串转换为char*,可以使用yourString.c_str()
C+C++文档:在C++ 11中有一个方法。对于旧版本,可以使用<代码>文本[0 ]。
。但请记住,c-string是以null结尾的字符串,vector的结尾可能没有null。为什么会涉及到向量?为什么不使用std::string?它正是为此而设计的!@Klaus可能有一个字节数组,它可能不仅包含字符串,也可能不像某些HTTP客户端实现中那样只包含单个字符串。我不确定我明白了:我拥有的是向量数据,我需要的是常量字符*我不能像在注释行中那样执行,data.begin(),data.end(),如果需要常量字符*,请使用字符串(begin(data),end(data)).c_str()谢谢。我怎么知道const char*的开始和结束?你能看到我在原始问题中发布的代码的功能吗?我正在尝试将vector转换为const char*我的意思是你必须先从你的vector创建一个字符串(使用Patryk解决方案)然后从这个字符串创建一个char*。好的,但这个函数我需要知道char*(注释函数TestLineWidth)的开头和结尾。事实上,如果您至少使用C++11,您可以使用非成员begin()和end()很抱歉,我仍然不明白。我可以从vector创建字符串,我可以将该字符串转换为const char*,但请看我的函数-我需要vector.begin()和vector.end(),它们必须转换为const char()*
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<char> data = {'h', 'e', 'l', 'l', 'o', '!'};
cout << string(begin(data), end(data)) << endl;
return 0;
}