C++ 如何将向量的char元素合并为string元素
我有两个向量。一个字符向量包含元素,每个元素存储段落的一个字符(包括点)。另一个是字符串向量,其每个元素应存储从第一个向量创建的单词 这是我的密码:C++ 如何将向量的char元素合并为string元素,c++,arrays,string,vector,compiler-errors,C++,Arrays,String,Vector,Compiler Errors,我有两个向量。一个字符向量包含元素,每个元素存储段落的一个字符(包括点)。另一个是字符串向量,其每个元素应存储从第一个向量创建的单词 这是我的密码: #include <iostream> #include <string> #include <vector> using namespace std; int main() { string source = "Vectors are sequence containers representin
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string source = "Vectors are sequence containers representing arrays that can change in size!";
vector<char> buf(source.begin(),source.end());
vector<string> word;
size_t n = 0;
size_t l = 0;
for (size_t k = 0; k < buf.size(); k++) {
if (buf[k] == ' ' || buf[k] == '\0') {
for (size_t i = n; i < k; i++) {
word[l] = word[l] + buf[i];
}
n = k + 1;
l++;
}
}
for (size_t m = 0; m < word.size(); m++) {
cout << word[m] << endl;
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
string source=“Vectors是表示可以改变大小的数组的序列容器!”;
向量buf(source.begin(),source.end());
向量词;
尺寸n=0;
尺寸=0;
对于(大小k=0;k cout如果问题是从字符串源代码创建单词向量,则有更简单的方法
例如,如果您记得输入提取操作符>
读取“words”(空格分隔的字符串),那么您可以将其用于可以读取字符串的输入流,如
如果你知道有两个迭代器,有一个类,你可以把它组合成一个简单的三语句程序:
std::string source = "Vectors are sequence containers representing arrays that can change in size!";
std::istringstream source_stream(source);
std::vector<std::string> words(
std::istream_iterator<std::string>(source_stream),
std::istream_iterator<std::string>());
这里有一个方法:
#include <stdio.h>
#include <algorithm>
#include <string>
#include <vector>
int main() {
std::string const source =
"Vectors are sequence containers representing arrays that can change in size!";
std::vector<std::string> words;
for (auto ibeg = source.begin(), iend = ibeg;;) {
iend = std::find(ibeg, source.end(), ' ');
words.emplace_back(ibeg, iend);
if (iend == source.end()) break;
ibeg = iend + 1;
}
for (auto const& w : words) puts(w.c_str());
}
#包括
#包括
#包括
#包括
int main(){
std::字符串常量源=
“向量是表示可以改变大小的数组的序列容器!”;
向量词;
对于(auto-ibeg=source.begin(),iend=ibeg;;){
iend=std::find(ibeg,source.end(),“”);
单词。安置回(ibeg,iend);
如果(iend==source.end())中断;
ibeg=iend+1;
}
for(auto-const&w:words)put(w.c_str());
}
有关将句子标记为单个单词的示例,请参见和。您永远不会将向量向后推
或调整大小
word
这样做word[l]=…
写得越界,因此未定义的行为向量buf
真的毫无用处。你可以用完全相同的方法直接在源代码上迭代。
#include <stdio.h>
#include <algorithm>
#include <string>
#include <vector>
int main() {
std::string const source =
"Vectors are sequence containers representing arrays that can change in size!";
std::vector<std::string> words;
for (auto ibeg = source.begin(), iend = ibeg;;) {
iend = std::find(ibeg, source.end(), ' ');
words.emplace_back(ibeg, iend);
if (iend == source.end()) break;
ibeg = iend + 1;
}
for (auto const& w : words) puts(w.c_str());
}