[英]How can I concatenate the elements of a vector of integers to a string in C++?
I've been trying to put every single element of a vector of integers into a string.我一直在尝试将整数向量的每个元素放入一个字符串中。 I want to achieve this by type casting the integers into strings, after that I cocatenate those "small strings" into a single big string, which is going to represent all the elements of that specific vector.我想通过将整数类型转换为字符串来实现这一点,然后我将这些“小字符串”连接成一个大字符串,它将代表该特定向量的所有元素。
This may look silly, but is really useful if you want to make a function that returns a vector like-a-thing, or etc.这可能看起来很傻,但如果你想制作一个返回类似矢量的 function 等,这真的很有用。
The only problem is that I'm getting an error on line 13, which says:唯一的问题是我在第 13 行遇到错误,它说:
error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(int&)’
13 | myString += (string) myVector[i];
| ^
and I don't have the slightest idea on why this is happening.我一点也不知道为什么会这样。 My code follows below:我的代码如下:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int myVector[5] = {1,2,3,4,5};
string myString = "";
for (int i =0; i < 5; i++)
{
myString += (string) myVector[i];
myString += "\n";
}
cout << myString << endl;
any help will be much appreciated.任何帮助都感激不尽。
You can usestd::to_string
to convert an int
to a std::string
.您可以使用std::to_string
将int
转换为std::string
。
Change this line:更改此行:
myString += (string) myVector[i];
To:到:
myString += std::to_string(myVector[i]);
Note: concatenating strings like that might not be so efficient due to temporary strings being created and destroyed (although it is likely that small strings optimization will kick in, so no additional heap allocations will take place).注意:由于创建和销毁临时字符串,像这样连接字符串可能效率不高(尽管小字符串优化很可能会启动,因此不会发生额外的堆分配)。
As @Someprogrammerdude commented, you can consider to use std::ostringstream
.正如@Someprogrammerdude 评论的那样,您可以考虑使用std::ostringstream
。
Side notes:旁注:
#include <string>
.您缺少#include <string>
。 You can use the fmt
library:您可以使用fmt
库:
fmt::join
will accept a range, in your case a vector of ints, and join its contents with a given separator (eg an empty string if you just want all of the elements together). fmt::join
将接受一个范围,在您的例子中是一个整数向量,并将其内容与给定的分隔符连接起来(例如,如果您只想将所有元素放在一起,则为空字符串)。fmt::format
will create a string with a given format, in this case just the contents of the joined vector. fmt::format
将创建一个具有给定格式的字符串,在本例中只是连接向量的内容。#include <fmt/ranges.h>
int main() {
int myVector[5] = {1,2,3,4,5};
auto myString = fmt::format("{}", fmt::join(myVector, ""));
fmt::print("{}\n", myString);
}
// Outputs: 12345
Or, simpler, if you don't need the string:或者,更简单,如果您不需要字符串:
int main() {
int myVector[5] = {1,2,3,4,5};
fmt::print("{}\n", fmt::join(myVector, ""));
}
The error you are getting is saying that the compiler cannot find a std::__cxx11::basic_string<char>::basic_string(int&)
function, ie, a std::string
constructor accepting an int&
.你得到的错误是说编译器找不到std::__cxx11::basic_string<char>::basic_string(int&)
function,即接受int&
的std::string
构造函数。
I'll add my own solution, as laid out in my comment:我将添加我自己的解决方案,如我的评论中所述:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
int main()
{
std::vector myvector = { 1, 2, 3, 4, 5 };
std::copy(std::begin(myvector), std::end(myvector),
std::ostream_iterator<int>(std::cout, "\n"));
}
Overload the output stream operator, and then you have something reusable for a lot of scenarios.重载 output stream 运算符,然后您就有了可在很多场景中重用的东西。
Based on the feedback below overloading is not the best answer, another approach here: https://www.onlinegdb.com/zDUjVbSTp根据下面的反馈,重载不是最好的答案,另一种方法在这里: https://www.onlinegdb.com/zDUjVbSTp
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
// Overloading operator<< will have many benefits.
// you can use it to output an array to std::cout directly
// or you can write it to a file or stringstream
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
os << "[";
bool comma = false;
for (const auto& value : values)
{
if (comma) os << ", ";
os << value;
comma = true;
}
os << "]";
return os;
}
int main()
{
std::vector<int> values{ 1,2,3,4,5 };
// write directly to std::cout
std::cout << "direct : " << values << "\n";
// adding array to a string
std::ostringstream os;
std::string string{ "output = " };
os << values;
string += os.str();
std::cout << string << "\n";
return 0;
}
You can use for_each algorithm as well to do the concatenation.您也可以使用for_each算法进行连接。
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6};
std::string all;
std::for_each(v.begin(), v.end(), [&, del=""](const int &e) {
all += std::to_string(e) + (&e == &v.back() ? "" : del);
});
std::cout << all << std::endl;
}
output: output:
123456
If you want to add a delimiter in between, just change the del
value in lambda capture.如果你想在两者之间添加分隔符,只需更改 lambda 捕获中的del
值即可。
std::for_each(v.begin(), v.end(), [&, del="-"](const int &e) {
all += std::to_string(e) + (&e == &v.back() ? "" : del);
});
Output: Output:
1-2-3-4-5-6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.