【问题标题】:Encoding two vectors in a function在函数中编码两个向量
【发布时间】:2014-09-10 17:55:56
【问题描述】:

嘿,我正在编写一个函数,它接受两个 std::vector<std::string> 并返回第三个 std::vector<std::string>。

该函数会将两个向量编码在一起并创建第三个向量。

我目前正在调试它以找出它不起作用的原因,并且我不断收到:vector subscript out of range。据我所知,它在这一行崩溃了:

if (file2[i].size() < file1[i].size())

我可以使用size() 来获取i 处元素的大小吗?

std::vector<std::string> Encode(std::vector<std::string> &file1,
                                std::vector<std::string> &file2)
{
    std::vector<std::string> file3;
    std::string temp;

    for (unsigned int i = 0; i < file1.size(); i++) {
        for (unsigned int x = 0; x < file1[i].size(); x++) {
            if (file2[i].size() < file1[i].size()) {
                for (unsigned int t = 0; t < file2[i].size(); t++) {
                    file3[i][x] = (int)file1[i][x] + (int)file2[i][t];
                }
            } else if (file2[i].size() > file1[i].size()) {
                file3[i][x] = (int)file1[i][x] + (int)file2[i][x];
            }

            if (file3[i][x] > 126) {
                file3[i][x] = file3[i][x] % 127;
            } else {
                file3[i][x] = file3[i][x] + 32;
            }
        }
    }
    return file3;
}

知道这里发生了什么吗?

【问题讨论】:

  • 首先猜测,vector file2 中的字符串比vector file1 中的字符串少。您只检查文件 1 的边界,而不检查文件 2。使用std::vector::at 运算符更安全。它会抛出一个越界异常。
  • 如果file2 的元素较少,那么一旦外循环到达file2 的末尾,file1、file2[i] 就会越界。
  • 知道如何让它循环回到起点吗?
  • 我希望它们迭代到 file1 的大小,因为如果文件 2 比文件 1 的大小短,我希望文件 2 循环回到开头。
  • 使用单独的计数器或使用模运算符。

标签: c++ c++11 vector


【解决方案1】:

我非常倾向于通过因式分解来简化。最底层是一个combine 函数,用于将两个chars 合二为一:

char combine(char a, char b)
{
    char result = a+b;
    if (result > 126)
        return result % 127;
    return result+32;
}

下一个级别是遍历两个可能不同大小的字符串中的每个字母。该算法通过“循环”较短的字符串来处理不同长度的字符串。

std::string mix(const std::string &first, const std::string &second)
{
    unsigned len1 = first.length();
    unsigned len2 = second.length();
    if (len1 < len2)
        return mix(second, first);
    std::string result;
    // if the strings are of different lengths, first is now the longer
    unsigned j=0;
    for (unsigned i=0; i < len1; ++i, ++j) {
        if (j >= len2)
            j = 0;
        result.push_back(combine(first[i], second[j]));
    }
    return result;
}

最后,vector 和 string 的组合要简单得多:

std::vector<std::string> Encode(const std::vector<std::string> &file1,
                                const std::vector<std::string> &file2)
{
    std::vector<std::string> file3;

    assert(file1.size() == file2.size());
    for (unsigned int i = 0; i < file1.size(); i++) {
        file3.push_back(mix(file1[i], file2[i]));
    }
    return file3;
}

请注意,代码当前使用assert 来确保两个vector 的长度相同,但这可能是人为的约束。真正的代码应该要么确保它们的长度相同,要么做其他事情来处理这种情况。由于尚不清楚您的功能打算做什么,因此我将其留给您来决定如何处理它,但使用 assert 作为占位符来提醒您确实需要解决它。

最后,一些使用C++11的驱动代码:

int main()
{
    std::vector<std::string> english{"one", "two", "three", "four"};
    std::vector<std::string> spanish{"uno", "dos", "tres", "cuatro"}; 

    auto result = Encode(english, spanish);

    std::copy(result.begin(), result.end(), 
              std::ostream_iterator<std::string>(std::cout, " "));
}

请注意,我使用push_back 附加到字符串的末尾,并使用const 声明传递的字符串。

【讨论】:

  • 嘿,一切看起来都不错,我试着环顾四周,却不知道是什么 (mix(file1[i], file2[i]));什么意思?
  • @Cellery72: mix 是我给将两个字符串混合在一起的函数的名称,因此mix(file1[i], file2[i]) 只需使用来自两个vectors 的两个字符串调用该函数。 mix 的源代码在我的回答中给出。
【解决方案2】:

试试这三组输入: 1. file1 大于 file2 2. file2 大于 file1 3. file1 的大小等于 file2。 让我们知道错误重现和未重现的情况。 我认为到了这个阶段,您将自己解决问题。 如果不, 写入重现错误的(最小的)file1 和 file2 的内容。

【讨论】:

    【解决方案3】:

    列举一些问题:

    -您 假设 file1 和 file2 具有相同大小或至少 file1 具有大小 (在另一种情况下会导致行 if (file2[i].size() &lt; file1[i].size()) { 中的内存访问无效)并且是没有为此检查功能。至少添加一个断言语句或一个检查。
    - 您正在初始化 file3 empty,稍后在函数中进行索引。
    -另一个问题是当file1[i]和file2[i]长度相同时会发生什么,这个选项在if-else中不覆盖,覆盖选项是而不是==。
    -您正在使用file3[i][x] 之类的语句访问无效内存,因为file3[i] 中的字符串初始化为空,因此不包含任何字符。

    这是我在不知道编码算法的确切步骤的情况下可以得到的更接近

    #include <iostream>
    #include <vector>
    #include <boost/lexical_cast.hpp>
    
    using namespace std;
    
    std::vector<std::string> Encode(std::vector<std::string> &file1,
        std::vector<std::string> &file2) {
    
        assert(file1.size() <= file2.size());
        std::vector<std::string> file3(file1.size());
        std::string temp;
    
        for (unsigned int i = 0; i < file1.size(); i++) {
            for (unsigned int x = 0; x < file1[i].size(); x++) {
                int enc = 0;
                if (file2[i].size() <= file1[i].size()) {
                    for (unsigned int t = 0; t < file2[i].size(); t++) {
                        enc = (int)file1[i][x] + (int)file2[i][t];
                    }
                }
                else if (file2[i].size() > file1[i].size()) {
                    enc = (int)file1[i][x] + (int)file2[i][x];
                }
    
                if (enc > 126) {
                    file3[i] += (enc % 127);
                }
                else {
                    file3[i] += (enc + 32);
                }
            }
        }
        return file3;
    }
    
    int main(int argc, char *argv[]) {
        std::vector<std::string> a{ "1", "2", "3" };
        std::vector<std::string> b{ "6", "7", "8" };
    
        for (const auto& s : a)
            std::cout << s << std::endl;
    
        for (const auto& s : b)
            std::cout << s << std::endl;
    
        auto c = Encode(a, b);
        for (const auto& s : c)
            std::cout << s << std::endl;
        return 0;
    }
    

    【讨论】:

    • the strings are immutable: 不,std::string 是可变的
    • 你为什么要assert(file1.size() &lt;= file2.size())? Encode 是否只能在这种情况下工作?这似乎是一个可怕的想法。如果file1.size() &gt; file2.size(),你如何让算法工作,然后扔掉assert。
    • @quantdev 抱歉,是的,std::string 是可变的、固定的,适用于多种语言
    • 断言用于在调试中检查运行时,如果条件成立,根据示例代码和我的响应中的代码,如果 file1.size() > file2.size() ,在执行if (file2[i].size() &lt;= file1[i].size()) { 行时,您将对某些索引的file2 进行索引。这种情况需要处理或表明不能发生(可能是设计限制),断言可以用于检查的条件不能发生(如果发生你想知道它)的情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 2019-10-30
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多