簡體   English   中英

向量值(字符串和整數)求和 C++

[英]Vector Values (String and Int) Summation C++

我已經從 Python 移到 C++,只是想知道如何對向量(列表)object 持有的值求和。 例如,在 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;
}

除了您沒有初始化 sum 變量之外,您的代碼工作正常。

這是一些不言自明的代碼,討論您可以使用的內容(基於您對問題的評論):

#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() ,則需要包含<iterator> 如果您不使用std::accumulate() ,您也可以刪除<numeric>

有關您在我的代碼中看到的任何不熟悉內容的文檔,請訪問https://en.cppreference.com/

程序有錯誤。 for循環中,您嘗試將 integer 與v.size()返回的unsigned long long int進行比較(在編譯器 arguments 中使用-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

如果您對 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 + " "; });  
}

Output:

15
Hello World abc 123 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM