繁体   English   中英

如何将整数向量的元素连接到 C++ 中的字符串?

[英]How can I concatenate the elements of a vector of integers to a string in C++?

我一直在尝试将整数向量的每个元素放入一个字符串中。 我想通过将整数类型转换为字符串来实现这一点,然后我将这些“小字符串”连接成一个大字符串,它将代表该特定向量的所有元素。

这可能看起来很傻,但如果你想制作一个返回类似矢量的 function 等,这真的很有用。

唯一的问题是我在第 13 行遇到错误,它说:

error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(int&)’
   13 |     myString += (string) myVector[i];
      |                                    ^

我一点也不知道为什么会这样。 我的代码如下:

#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;

任何帮助都感激不尽。

您可以使用std::to_stringint转换为std::string

更改此行:

myString += (string) myVector[i];

到:

myString += std::to_string(myVector[i]);

注意:由于创建和销毁临时字符串,像这样连接字符串可能效率不高(尽管小字符串优化很可能会启动,因此不会发生额外的堆分配)。
正如@Someprogrammerdude 评论的那样,您可以考虑使用std::ostringstream

旁注:

  1. 您缺少#include <string>
  2. 为什么“使用命名空间标准;” 被认为是不好的做法? .

您可以使用fmt库:

  1. fmt::join将接受一个范围,在您的例子中是一个整数向量,并将其内容与给定的分隔符连接起来(例如,如果您只想将所有元素放在一起,则为空字符串)。
  2. 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

或者,更简单,如果您不需要字符串:

int main() {
  int myVector[5] = {1,2,3,4,5};
  fmt::print("{}\n", fmt::join(myVector, ""));
}

你得到的错误是说编译器找不到std::__cxx11::basic_string<char>::basic_string(int&) function,即接受int&std::string构造函数。

您可以使用std::stringstream

#include <iostream>
#include <string>
#include <sstream>
int main()
{
    int myVector[5] = {1,2,3,4,5};
    std::string myString;

    std::stringstream sstream;
    for (auto i : myVector)
        sstream << i;

    sstream >> myString;
    std::cout << myString;
}

链接

我将添加我自己的解决方案,如我的评论中所述:

#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"));
}

重载 output stream 运算符,然后您就有了可在很多场景中重用的东西。

根据下面的反馈,重载不是最好的答案,另一种方法在这里: 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;
}

您也可以使用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:

123456

如果你想在两者之间添加分隔符,只需更改 lambda 捕获中的del值即可。

std::for_each(v.begin(), v.end(), [&, del="-"](const int &e) { 
        all += std::to_string(e) + (&e == &v.back() ? "" : del); 
    });

Output:

1-2-3-4-5-6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM