【问题标题】:Vector Values (String and Int) Summation C++向量值(字符串和整数)求和 C++
【发布时间】:2024-01-16 04:18:01
【问题描述】:

我已经从 Python 迁移到 C++,只是想知道如何对向量(列表)对象所持有的值求和。例如,在python中,我可以使用下面的代码:

totalSum = 0
myList = [1,2,3,4,5]

for i in myList:
    totalSum += i

print(totalSum)
// Output:
15

但是,我想学习在 C++ 中执行此操作的方法

totalSum = ""
myList = ["Hello", "World!"]

for i in myList:
    totalSum += i
    totalSum += " "

print(totalSum)
//Output:
Hello World!

而这个是给字符串组合的。

能否请您提供如何在 c++ 中执行此操作?

我在C++中试过下面的代码来测试,但是编译不成功:

#include <iostream>
#include <vector>
using namespace std;


int main()
{
    
    // A random list/vector here:
    vector <double> v = {1, 2, 3, 4, 5};

    // Declaring the final string to gather all the vector values:
    int sum;

    // Iterating through the vector
    for (int i = 0; i < v.size(); i++) {
        sum += v[i];
    }
    
    cout << sum;

    return 0;
}

【问题讨论】:

  • 你在寻找std::accumulate吗?
  • 这也适用于字符串吗?
  • 如果你能想出一些东西来描述积累/总结字符串的含义并为此提供合适的函子,那么当然。
  • 为什么代码不能编译?你得到什么错误?
  • 只是一个常规的 vs 调试器错误

标签: python c++ list vector sum


【解决方案1】:

程序有错误。在for 循环中,您尝试将整数与v.size() 返回的unsigned long long int 进行比较(在编译器参数中使用-Wall 模式来获取它)。

使用每种语法,方法定义如下:

#include <iostream>
#include <vector>

int main(void) {
    std::vector <std::string> v = {"Hello", "World"};
    std::string sum;

    for (auto i : v) {
        sum += i;
        sum += ' ';
    }
    
    std::cout << sum << std::endl;

    return 0;
}

这将打印:

Hello World

【讨论】:

  • 正是我想要的,非常感谢!
【解决方案2】:

如果您对 STL 算法感兴趣,可以使用std::accumulate 来实现:

#include <vector>
#include <numeric>
#include <string>
#include <iostream>

int main()
{
    std::vector <double> v = {1, 2, 3, 4, 5};
    std::cout << std::accumulate(v.begin(), v.end(), 0.0) << "\n"; 

    std::vector<std::string> s = {"Hello", "World", "abc", "123"};
    std::cout << std::accumulate(s.begin(), s.end(), std::string(), 
                                [](auto& total, auto& str) { return total + str + " "; });  
}

输出:

15
Hello World abc 123 

【讨论】:

  • 非常感谢
【解决方案3】:

除了您没有初始化 sum 变量之外,您的代码工作正常。

这是一些不言自明的代码,讨论您可以使用的内容(基于您问题上的 cmets):

#include <iostream>
#include <numeric>
#include <string>
#include <vector>

int main() {

    // For strings:

    std::string str;
    std::vector<std::string> v = {"Hello", "World!"};

    // Method 1: Using range-based for loop:
    for (auto &&i : v) {
        str += i;
        str += " ";
    }
    std::cout << str << std::endl;

    // Method 2: Using std::accumulate():
    str = std::accumulate(v.begin(), v.end(), std::string(), [](std::string a, std::string b) {
        return std::move(a) + b + " ";
    });
    std::cout << str << std::endl;

    // Method 3: The usual for-loop:
    str = "";
    for (size_t i = 0; i < v.size(); ++i) {
        str += v.at(i); // str += v[i];
        str += " ";
    }
    std::cout << str << std::endl;

    // Method 4: Using iterators:
    str = "";
    for (auto i = v.begin(); i < v.end(); ++i) { // for (auto i = std::begin(v); i < std::end(v); std::advance(i))
        str += *i;
        str += " ";
    }
    std::cout << str << std::endl;

    // For numbers:

    std::vector<int> v2  = {1, 2, 3, 4, 5};
    int sum = 0;

    // Method 1: Using range-based for loop:
    for (auto &&i : v2)
        sum += i;
    std::cout << sum << std::endl;

    // Method 2: Using std::accumulate():
    sum = std::accumulate(v2.begin(), v2.end(), 0);
    std::cout << sum << std::endl;

    // Method 3: The usual for-loop:
    sum = 0;
    for (size_t i = 0; i < v2.size(); ++i)
        sum += v2.at(i); // sum += v2[i]
    std::cout << sum << std::endl;

    // Method 4: Using iterators:
    sum = 0;
    for (auto i = v2.begin(); i < v2.end(); ++i) // for (auto i = std::begin(v2); i < std::end(v2); std::advance(i))
        sum += *i;
    std::cout << sum << std::endl;

    return 0;
}

如果您使用的是 C++14 或更高版本,您可以将传递给 std::accumulate 的 lamda 的参数列表从 (std::string a, std::string b) 替换为 (auto a, auto b)

如果您使用的是std::begin()std::end()std::advance(),则需要包含&lt;iterator&gt;。如果您不使用std::accumulate(),也可以删除&lt;numeric&gt;

有关您在我的代码中看到的任何不熟悉内容的文档,请访问https://en.cppreference.com/

【讨论】:

    最近更新 更多