【问题标题】:How to copy characters into string vector如何将字符复制到字符串向量中
【发布时间】:2019-12-08 07:49:48
【问题描述】:

尝试从字符向量复制到字符串向量在解决方案的多次尝试中均未成功

在复制之前为向量分配内存允许 std::copy 在放置在“OutputIterator 结果”(基于函数模板)时正常工作。我尝试过:

std::copy(char1.begin(), char1.end(), v1.begin());

然而,这也是不成功的。使用 back_inserter 返回错误 c2679 "binary '=': no operator found which take a right-hand operand of type 'char' (或没有可接受的转换)。

输入文件位于:https://adventofcode.com/2018/day/2

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iterator>
#include <cstdio>



    int main() {

        std::string field1;
        std::string field2;
        char characters;

        std::vector<char>::iterator ptr;
        std::vector<char>::iterator ptr2;

        std::vector<char> char1;
        std::vector<char> char2;

        int size = 0;

        std::ifstream inFile;

        inFile.open("C:\\Users\\Administrator\\Desktop\\c++ files\\input2.txt");

        if (!inFile) {

            std::cout << "abort";

            return 1;

        }

        while (inFile >> characters) {          //read variables from input stream

            char1.push_back(characters);

        }

        std::vector<std::string> v1(6500);

        std::copy(char1.begin(), char1.end(), std::back_inserter(v1)); 

        inFile.close();

        return 0;

    }

    //26

期望向量 v1 保存向量 char1 中的值。我假设问题源于 v1 与 char1 的数据类型,但是,我还没有找到具体的解决方案。我不想直接读入字符串向量;因此我目前的问题。

【问题讨论】:

  • 即使在查看了链接之后,也不清楚您想要的结果是什么......每个字符串都有一个字符的字符串向量?一个包含所有字符的单个字符串的向量?还是一个字符串向量,其中字符被某些分隔符或其他标准分割?

标签: c++11 std stdvector


【解决方案1】:

我不确定你想达到什么目标。这里举几个例子:

#include <string>
#include <vector>

int main()
{
    std::string str1{ "Just for an example" }; // You can read it from a file
    std::vector<std::string> vct_str1(32); // Lets say it has 32 std::string items
    std::vector<std::string> vct_str2(32); // Lets say it has 32 std::string items

    // **** A. Copy from std::string to std::vector<char>: ****
    std::vector<char> vct_ch(str1.begin(), str1.end()); // On construction
           // Or later: vct_ch.assign(str1.begin(), str1.end());

    // **** B. Copy from std::vector<char> to std::string: ****
    std::string str2(vct_ch.begin(), vct_ch.end()); // On construction
           // Or later: str2.assign(vct_ch.begin(), vct_ch.end());

    // **** C. Copy from std::vector<char> to std::vector<std::string>: ****
    vct_str1[0].assign(vct_ch.begin(), vct_ch.end()); // Which is similar to B

    // **** D. Source & Dest Types same as in Case-C But char per std::string: ****
    int i = 0;
    vct_str2.resize(vct_ch.size());
    for (auto item : vct_ch)
        vct_str2[i++] = item;

    return 0;
}

【讨论】:

  • 方法A和B至少可以通过vectorstring的构造函数简单地完成:std::vector&lt;char&gt;(str.begin(), str.end())std::string(vec.begin(), vec.end())
猜你喜欢
  • 2022-01-05
  • 2016-05-03
  • 1970-01-01
  • 2015-03-28
  • 2017-12-29
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多